【问题标题】:Django Inline Formsets - clean() method not workingDjango Inline Formsets - clean() 方法不起作用
【发布时间】:2017-12-08 03:38:47
【问题描述】:

所以我有一个由 django.forms.inlineformset_factory 创建的 django 内联表单集,其中包含一个父项:ParentCount,和子项: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

我认为这会为表单集中的每个 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 method() 都不是从 ChildCountForm 派生的,而是从 BaseModelForm 派生的。如果我在 pdb 中的该行实例化一个空的 ChildCountForm,它表示它从 ChildCountForm 派生了 clean 方法,但 self.forms 中的“form”对象没有。这是为什么呢?

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

【问题讨论】:

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


    【解决方案1】:

    你误解了inlineformset_factory 的作用。它为子表单创建表单集,所以如果你想指定一个自定义表单,你应该传入 ChildCountForm。

    还请注意,调用每个表单的 clean 方法是默认行为,因此无需重写表单集来执行此操作。

    【讨论】:

    • 传入 ChildCountForm 导致没有表单被渲染?
    猜你喜欢
    • 2013-08-01
    • 2013-07-17
    • 2018-10-18
    • 1970-01-01
    • 2013-09-06
    • 1970-01-01
    • 2021-10-09
    • 2022-01-04
    • 2015-09-18
    相关资源
    最近更新 更多