Django Inlineformset Factory验证不起作用

时间:2019-02-06 13:36:34

标签: django django-models django-forms django-views

我有两种形式,一种是供应商详细信息,一种是供应商的联系方式,因此我使用inlineformset_factory合并两种形式,并能够在添加供应商时添加联系人,并且该功能运行良好。唯一的问题是它显示了供应商表单的表单验证错误,而不是联系人(inlineformset)的表单验证错误。

Forms.py

class SupplierForm(forms.ModelForm):

class Meta:
    model = Supplier
    fields = ('category','name','alternate_name','logo','address1','address2','city','zip','region','region_code','country','country_code','detail')

class ContactForm(forms.ModelForm):

class Meta:
    model = Contact
    fields = ('contact_type','job_title','first_name','last_name','phone','email','skype','wechat')

def clean(self):
    if any(self.errors):
        return

ContactFormSet = forms.inlineformset_factory(Supplier, Contact, form=ContactForm, extra=1)

Views.py

class CreateSupplierView(LoginRequiredMixin,CreateView):

form_class = SupplierForm
model = Supplier

def form_valid(self, form):
    context = self.get_context_data()
    contacts = context['contacts']
    with transaction.atomic():
        self.object = form.save()

        if contacts.is_valid():
            contacts.instance = self.object
            contacts.save()
    return super(CreateSupplierView, self).form_valid(form)

def get_context_data(self, **kwargs):
    context = super(CreateSupplierView, self).get_context_data(**kwargs)

    if self.request.POST:
        context['contacts'] = ContactFormSet(self.request.POST)
    else:
        context['contacts'] = ContactFormSet()
    return context

如果供应商表单无效,则将其转发以添加/编辑表单并显示错误,但是如果供应商表单良好,则唯一的联系人有错误,则将其转发至供应商列表并且不显示任何错误。

如果联系人表单无效,如何显示相同的编辑/添加表单,但出现错误?

0 个答案:

没有答案