重复输入' 2-1'用于django中的密钥错误处理?

时间:2016-04-20 14:59:38

标签: django django-models django-forms

我有一个模型,其中字段userinvoice_number都设置为唯一

class Meta:
        unique_together = (("user", "invoice_number"),)

现在,当我测试此表单时,第一条记录与唯一invoice_number得到保存并正常工作。 但是,当我尝试使用相同的invoice_number django保存表单时,显示错误为:

(1062, "Duplicate entry '2-1' for key 'invoice_serviceinvoice_user_id_76850a1_uniq'")

如何避免此错误并向用户This is duplicate invoice number.显示消息?

views.py

@login_required
def createinvoice(request):
    new_formset=createinvoiceformset(instance=serviceinvoice())
    if request.method == 'POST':
        inv_form=createinvoiceform(data=request.POST,user=request.user)        
        if inv_form.is_valid():
            new_form=inv_form.save(commit=False)
            new_form.user=request.user
            new_formset=createinvoiceformset(request.POST,instance=new_form)
            if new_formset.is_valid():
                new_form.save()
                hero=new_formset.save(commit=False)
                for hero1 in hero:
                    hero1.user=request.user
                    hero1.save()
                return HttpResponse('Invoice created')
    else:
        inv_form=createinvoiceform(request.user)
    return render(request,'account/createinvoice.html',{'inv_form':inv_form,'new_formset':new_formset})

forms.py

class createinvoiceform(forms.ModelForm):

    def __init__(self,user, *args, **kwargs):
        super(createinvoiceform, self).__init__(*args, **kwargs)
        self.fields["invoice_receivable"].queryset=Receivables.objects.filter(user=user)
        self.fields['invoice_receivable'].widget.attrs.update({'placeholder': 'invoice_receivable','class': 'input-calss_name'})

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

0 个答案:

没有答案