Django内联Formsets - clean()方法不起作用

时间:2017-07-04 15:33:38

标签: python django django-forms formset inline-formset

所以我有一个由django.forms.inlineformset_factory创建的django内联formset,它包含一个父:ParentCount和child:ChildCount。

在ChildCount表单中,我已经重写了clean方法:

class ChildCountForm(ModelForm):
    class Meta:
        model = ChildCount
        exclude = ["name"]

    def clean(self):
        cleaned_data = super(ChildCountForm, self).clean()

        att1 = cleaned_data.get("att1")
        att2 = cleaned_data.get("att2")

        if att1 == "I3i" and att2 is None:
            msg = "Require att2 information for I3i attribute"
            self._errors['att2'] = self.error_class([msg])

        """Returns the cleaned data"""
        return cleaned_data

我认为这将在formset中调用每个ChildForm,因为inlineformset_factory是使用自定义表单类定义的,它使用逻辑:

class CustomInlineFormset(BaseInlineFormSet):
    """used to pass in the constructor of inlineformset_factory"""
    def clean(self):
        """forces each clean() method on the ChildCounts to be called"""
        super(BaseInlineFormSet, self).clean()
        for form in self.forms:
            form.clean()

ChildFormSet = inlineformset_factory(ParentCount, ChildCount,
                                     form=ParentCountForm,
                                     extra=1,
                                     max_num=30,
                                     formset=CustomInlineFormset)

但是,在表单的这一点上,每个表单的clean方法()不是从ChildCountForm派生的,它是从BaseModelForm派生的。如果我在pdb中的那一行实例化一个空的ChildCountForm,它表示它从ChildCountForm派生出clean方法,但self.forms中的'form'对象却没有。这是为什么?

如何让我的自定义clean()方法为每个ChildForm运行?

1 个答案:

答案 0 :(得分:1)

你误解了inlineformset_factory正在做什么。它为子表单创建formset,因此如果要指定自定义表单,则应在ChildCountForm中传递。

另请注意,调用每个表单的clean方法是默认行为,因此不需要覆盖formset来执行此操作。

相关问题