Отображение поля в виде внешнего ключа в шаблоне

class Product(models.Model):
    
    model=models.CharField(max_length=50, null=True)
    serial=models.CharField(max_length=50, null=True)
    hd_size=models.CharField(max_length=50,null=True)
    ram=models.CharField(max_length=50, null=True)
    processor=models.CharField(max_length=50, null=True)
    product_type = models.CharField(max_length=10, null=True)
    date_purchased = models.DateField(null=True)
    date_created = models.DateTimeField(default=timezone.now)
    date_updated = models.DateTimeField(auto_now=True)
    employee = models.ForeignKey(Employee, on_delete=models.SET_NULL, null=True)

Я пытаюсь отобразить данные из этой модели, но столбец внешнего ключа "employee" не отображается в шаблоне

Вот мой шаблон

<div class="container-fluid">
    <form method= 'POST' id="product-form">
        {% csrf_token %}
        <input type="hidden" name="id" value="{{ product.id }}">
        <div class="form-group mb-3 ">
            <label for="model" class="control-label">Model</label>
            <input type="text" class="form-control rounded-0" id="model" name="model" value="{{ product.model}}" required>
                </div>
        <div class="form-group mb-3 ">
            <label for="serial" class="control-label">Serial No</label>
            <input type="text" class="form-control rounded-0" id="serial" name="serial" value="{{ product.serial}}" required>
        </div>
        <div class="form-group mb-3 ">
            <label for="hd_size" class="control-label">HD Size</label>
            <input type="text" class="form-control rounded-0" id="hd_size" name="hd_size" value="{{ product.hd_size}}" required>
        </div>
        <div class="form-group mb-3 ">
            <label for="ram" class="control-label">RAM</label>
            <input type="text" class="form-control rounded-0" id="ram" name="ram" value="{{ product.ram}}" required>
        </div>
        <div class="form-group mb-3 ">
            <label for="processor" class="control-label">Processor</label>
            <input type="text" class="form-control rounded-0" id="processor" name="processor" value="{{ product.processor}}" required>
        </div>
        <div class="form-group mb-3 ">
            <label for="product_type" class="control-label">Type</label>
            <input type="text" class="form-control rounded-0" id="product_type" name="product_type" value="{{ product.product_type}}" required>
        </div>
            <div class="form-group mb-3 ">
                <label for="date_purchased" class="control-label">date purchased</label>
                <input type="date" class="form-control rounded-0" id="date_purchased" name="date_purchased" value="{{ product.date_purchased}}" required>
            </div>
            <div class="form-group">
                <label for="employee">Employee:</label>
                <select class="form-control" id="employee" name="employee">
                  {% for employee in form.employee.field.queryset %}
                  <option value="{{ employee.address }}">{{ employee.address }}</option>
                  {% endfor %}
                </select>
              </div>     
  
    </form>
</div>

Поле с внешним ключом должно позволить мне иметь выпадающий список, в котором я могу выбирать из списка адреса электронной почты сотрудников из таблицы сотрудников

Вот мой views.py

# product
@login_required
def product_mgt(request):
    context['page_title'] = "Computer List"
    products = Product.objects.all()
    context['products'] = products

    return render(request, 'product_mgt.html', context)

@login_required
def save_product(request):
    resp = {'status':'failed','msg':''}
    if request.method == 'POST':
        if (request.POST['id']).isnumeric():
            product = Product.objects.get(pk=request.POST['id'])
        else:
            product = None
        if product is None:
            form = SaveProduct(request.POST)
        else:
            form = SaveProduct(request.POST, instance= product)
        if form.is_valid():
            form.save()
            
            messages.success(request, 'Computer has been saved successfully.')
            resp['status'] = 'success'
            
        else:
            for fields in form:
                for error in fields.errors:
                    resp['msg'] += str(error + "<br>")
    else:
        resp['msg'] = 'No data has been sent.'
    return HttpResponse(json.dumps(resp), content_type = 'application/json')
     

Спасибо. Мне удалось решить проблему, создав отдельную форму для ввода поля внешнего ключа, а затем сохранить с помощью этого представления

def assign_employee_to_product(request, product_id):
    product = get_object_or_404(Product, pk=product_id)
    if request.method == "POST":
        form = AssignEmployeeForm(request.POST, instance=product)
        if form.is_valid():
            form.save()
            messages.success(request, 'Employee has been assigned a computer successfully.')
            
            
    else:
        form = AssignEmployeeForm(instance=product)
    return render(request, 'assign.html', {'form': form, 'product': product})
Вернуться на верх