视图和模板为m2m与通过

时间:2018-03-18 00:35:33

标签: django django-forms django-templates django-views

在我的应用程序中,我需要存储已知产品(产品)的发票(发票)来计算每个卖家(用户)的积分。我正在尝试创建表单以插入基本发票数据以及带有已售产品信息的内联表单。为了处理它,我创建了这样的模型:

class Product(models.Model):
    group = models.CharField(max_length = 200, blank = False)
    mark = models.CharField(max_length = 200, blank = True)
    points = models.IntegerField(blank = False)

class Invoice(models.Model):
    price = models.FloatField(blank=False)
    file = models.FileField(blank=False)
    product = models.ManyToManyField(Product, through='Sold')
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    date = models.DateField()
    date_created = models.DateField(auto_now_add=True)
    date_updated = models.DateField(auto_now=True)

class Sold(models.Model):
    invoice = models.ForeignKey(Invoice, on_delete=models.CASCADE)
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    quantity = models.PositiveIntegerField(default=1)

我尝试通过django-admin管理它,它可以正常使用admin.py:

class ProductTabular(admin.TabularInline):
    model = Invoice.product.through


class InvoiceAdmin(admin.ModelAdmin):
    inlines = [ProductTabular]
    exclude = ('product', )

    class Meta:
        model = Invoice


admin.site.register(Invoice, InvoiceAdmin)

但是我无法在自己的模板中创建这样的表单。请问你能帮我看一下views.py和模板,以获得与django-admin相同的结果吗?

我尝试使用带有inlineformset_factory的invoce表单来销售模型,但我无法弄清楚如何保存它。谢谢你的帮助!

0 个答案:

没有答案