在Django Model Form中显示ManytoMany对象的所有字段

时间:2018-10-23 02:58:15

标签: django django-forms

我正在做一个简单的发票应用程序,我的Django模型表格遇到了问题。窗体显示所有ManytoManyfields对象,但我想显示所有字段,而不仅仅是对象名。

我的模型。py:

from django.db import models
import datetime
from django.urls import reverse

# Create your models here.


class Product(models.Model):
    item_name        = models.CharField(max_length=100)
    chinese_name     = models.CharField(max_length=100)
    erp_number       = models.CharField(max_length=20)
    unit             = models.CharField(max_length=8)
    photo            = models.ImageField(blank=True, null=True)
    price_usd        = models.DecimalField(max_digits=8, decimal_places=2)
    price_eur        = models.DecimalField(max_digits=8, decimal_places=2)

    def __str__(self):
        return self.item_name

class Batch(models.Model):
    batch_name = models.CharField(max_length=100)
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    quantity = models.DecimalField(max_digits=5, decimal_places=0)

    def __str__(self):
        return self.batch_name

class Invoice(models.Model):
    invoice_no          = models.CharField(max_length=30, default="Proforma Invoice 2018102300001")
    products = models.ManyToManyField(Product)
    total = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True)
    date              = models.DateField(auto_now_add=False,auto_now=False, default=datetime.datetime.now())

    def __str__(self):
        return self.invoice_no

    def get_absolute_url(self):
        return reverse('invoice_detail',kwargs = {'pk':self.pk})

我的forms.py:

from django import forms
from django.forms import modelformset_factory, inlineformset_factory
from .models import Invoice, Product
from django.forms.widgets import CheckboxSelectMultiple

class InvoiceForm(forms.ModelForm):
    invoice_no =forms.CharField(widget=forms.TextInput(attrs={'size':40}),initial='Proforma Invoice 2018102300001')
    date = forms.DateField(widget = forms.SelectDateWidget)
    class Meta:
        model = Invoice
        fields = '__all__'

    def __init__(self, *args, **kwargs):
        super(InvoiceForm, self).__init__(*args, **kwargs)

        self.fields["products"].widget = CheckboxSelectMultiple()
        self.fields["products"].queryset = Product.objects.all()

我的模板:

{%  extends 'base.html' %}
{%  block content %}
<!DOCTYPE html>
<html lang="en">
<body>
<form  method="POST" action="">
    {% csrf_token %}
    <div clas="row">
        <p style="width:20px">{{ form.invoice_no }}</p>
        <p>{{ form.date }}</p>
    </div>
    <div class ="row">
        <div class="col-md-12">
            <div class="table-responsive">
                <table class="table">
                  <thead>
                    <tr>
                      <th scope="col" >Photo</th>
                      <th scope="col">Name</th>
                      <th scope="col">ERP number</th>
                      <th scope="col">Unit</th>
                      <th scope="col">Price (USD)</th>
                      <th scope="col">Price (EUR)</th>
                    </tr>
                  </thead>
                  <tbody>
                  {% for product in form.products.all %}
                    <tr>
                      <th scope="row"></th>
                      <td>{{product.item_name}}</td>
                      <td>{{form.products.erp_number}}</td>
                      <td>product.unit</td>
                      <td>product.price_usd</td>
                      <td>product.price_eur</td>
                    </tr>
                  {% endfor %}
                  </tbody>
                </table>
            </div>
        </div>
    </div>
<input type="submit" value="Submit">
</form>
</body>
</html>
{%  endblock %}

如您所见,我正在尝试使用{% for product in form.products.all %}来访问产品模型的字段,因为它不起作用。我一直在寻找关于stackoverflow的解决方案,但没有找到正确的答案。是一种不仅显示objectname而且仍然保留self.fields["products"].widget = CheckboxSelectMultiple()小部件的方法吗?

0 个答案:

没有答案