Django多个相关表单数据处理错误

时间:2016-04-19 11:04:11

标签: python django forms

我正在尝试制作 app.Model.py

class serviceinvoice(models.Model):
    user=models.ForeignKey(User,related_name='invoice')    
    invoice_number=models.PositiveIntegerField()
    #invoice_no = models.CharField(max_length = 500, default = increment_invoice_number, null = True, blank = True)
    invoice_date = models.DateField()
    invoice_receivable=models.ForeignKey(Receivables,null=True)
    total_amount=models.DecimalField(decimal_places=2,max_digits=20)
    total_amountwithtax=models.DecimalField(decimal_places=2,max_digits=20)

    def __str__(self):
        return self.invoice_number

class serviceinvoiceitems(models.Model):
    user=models.ForeignKey(settings.AUTH_USER_MODEL,related_name='serviceinvoiceitems')
    invoice_number=models.ForeignKey(serviceinvoice)
    Product=models.CharField(max_length=1000,null=True)
    UOM=models.CharField(max_length=100,null=True)
    Quantity=models.FloatField(null=True)
    Rate=models.FloatField(null=True)
    Tax_rate=models.FloatField(null=True)

    def __str__(self):
        return self.invoice_number

forms.py

class createinvoiceform(forms.ModelForm):
    class Meta:
        model=serviceinvoice
        exclude=('user',)
        widgets = {
            'invoice_date': forms.DateInput(attrs={'class':'datepicker'}),
        }

class invoiceitemform(forms.ModelForm):
    class Meta:
        model=serviceinvoiceitems
        exclude=('user','invoice_number',)

views.py

@login_required
def createinvoice(request):
    if request.method == 'POST':
        inv_form=createinvoiceform(data=request.POST)
        inv_item=invoiceitemform(data=request.POST)
        if inv_form.is_valid() and inv_item.is_valid():
            new_form=inv_form.save(commit=False)
            new_form.user=request.user
            new_form.save()
            new_invitem=inv_item.save(commit=False)
            new_invitem.user=request.user
            new_invitem.invoice_number=request.invoice_number
            new_invitem.save()
            return HttpResponse('Invoice created')
    else:
        inv_form=createinvoiceform()
        inv_item=invoiceitemform()
        inv_form.fields["invoice_receivable"].queryset=Receivables.objects.filter(user=request.user)
    return render(request,'account/createinvoice.html',{'inv_form':inv_form,'inv_item':inv_item})

表单显示在模板中,但不会被视图处理。

获取错误,

  

(1048,"专栏' invoice_number_id'不能为空")。

请指导:

  1. 我如何处理此表单,因为第二种表单将使用第一种形式的外键。

  2. 模板中有多种方法可以多次显示第二种形式吗?

1 个答案:

答案 0 :(得分:0)

将发票编号设为非必填字段

<强> models.py

invoice_number=models.ForeignKey(serviceinvoice, null=True, blank=True,
                                 default=None)