【发布时间】: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