Django内联Formset自定义验证一次只验证单个Formset

时间:2011-01-01 23:39:22

标签: django inline-formset

我正在使用Django,并且有一个带有两个额外内联表单集的表单。我想验证每个formset包含至少一个填充的表单。我编写的代码使得它可以工作,但它一次只适用于每个formset。如果我在没有填充任何表单集表单的情况下提交表单,则只有第一个表单显示验证错误。如果我然后填充第一个formset表单,并将第二个表单设置为空白,则第二个表单错误。

如果两个表单都无效,我希望错误出现在这两个表单上。

表单只是标准ModelForm个实例。这是我的观点:

class RequiredBaseInlineFormSet(BaseInlineFormSet):
    def clean(self):
        self.validate_unique()
        if any(self.errors):
            return
        if not self.forms[0].has_changed():
            raise forms.ValidationError("At least one %s is required" % self.model._meta.verbose_name)

def create(request):
    profile_form = ProfileForm(request.POST or None)
    EmailFormSet = inlineformset_factory(Profile, Email, formset=RequiredBaseInlineFormSet, max_num=5, extra=5, can_delete=False)
    email_formset = EmailFormSet(request.POST or None)
    PhoneFormSet = inlineformset_factory(Profile, Phone, formset=RequiredBaseInlineFormSet, max_num=5, extra=5, can_delete=False)
    phone_formset = PhoneFormSet(request.POST or None)
    if profile_form.is_valid() and email_formset.is_valid() and phone_formset.is_valid():
        profile = profile_form.save()
        emails = email_formset.save(commit=False)
        for email in emails:
            email.profile = profile
            email.save()
        phones = phone_formset.save(commit=False)
        for phone in phones:
            phone.profile = profile
            phone.save()
        messages.add_message(request, messages.INFO, 'Profile successfully saved')
    return render_to_response(
        'add.html', {
            'profile_form': profile_form,
            'email_formset': email_formset,
            'phone_formset': phone_formset
        }, context_instance = RequestContext(request)
    )

这是我模板的形式,因为它很有用:

<form action="" method="post" accept-charset="utf-8">
    {{ email_formset.management_form }}
    {{ phone_formset.management_form }}
    {{ profile_form|as_uni_form }}
    <div class="formset-group" id="email_formset">
        {{ email_formset.non_form_errors }}
        {% for email_form in email_formset.forms %}
            <div class='form'>
                {{ email_form|as_uni_form }}
            </div>
        {% endfor %}
    </div>
    <div class="formset-group" id="phone_formset">
        {{ phone_formset.non_form_errors }}
        {% for phone_form in phone_formset.forms %}
            <div class='form'>
                {{ phone_form|as_uni_form }}
            </div>
        {% endfor %}
    </div>
    <input type="submit" value="Save Profile" id="submit">
</form>

2 个答案:

答案 0 :(得分:2)

为要在其上进行验证的每个表单调用is_valid()函数。在你的例子中,如果a.is_valid和b.is_valid anc c.is_valid ...如果a为false,则b和c将永远不会被调用。尝试不同的东西,例如:

alpha=a.is_valid()
beta=b.is_valid()
gamma=c.is_valid()

if alpha and beta and gamma: 
  do stuff

答案 1 :(得分:0)

我有一个类似的问题,问题是由于Django如何处理额外的表单字段,额外的表单没有得到验证。看看:Django Formset.is_valid() failing for extra forms