Django如何覆盖自定义窗体的子类中的clean()方法?
我创造了这样的自定义验证的自定义窗体:现在Django如何覆盖自定义窗体的子类中的clean()方法?
class MyCustomForm(forms.Form):
# ... form fields here
def clean(self):
cleaned_data = self.cleaned_data
# ... do some cross-fields validation here
return cleaned_data
,这种形式与子类有其自身的清洁方法的另一种形式。
触发clean()方法的正确方法是什么?
目前,这是我做的:
class SubClassForm(MyCustomForm):
# ... additional form fields here
def clean(self):
cleaned_data = self.cleaned_data
# ... do some cross-fields validation for the subclass here
# Then call the clean() method of the super class
super(SubClassForm, self).clean()
# Finally, return the cleaned_data
return cleaned_data
看来工作。但是,这使得两个clean()方法返回cleaned_data
,这在我看来有点奇怪。
这是正确的方法吗?
你做得很好,但你应该从超级呼叫负载cleaned_data这样的:
class SubClassForm(MyCustomForm):
# ... additional form fields here
def clean(self):
# Then call the clean() method of the super class
cleaned_data = super(SubClassForm, self).clean()
# ... do some cross-fields validation for the subclass
# Finally, return the cleaned_data
return cleaned_data
谢谢@Mounir。其中一个问题是:您建议的方式,'cleaned_data'将包含超类的字段。我还需要验证子类上的字段。我该怎么做? – user1102018 2013-04-26 11:13:44
继续我的评论,也许应该是这样的:'clean_sub_data = self.cleaned_data'后面跟着'cleaned_data.update(cleaned_sub_data)'。然后我可以返回'cleaned_data' – user1102018 2013-04-26 11:24:04
你做正确。 – 2013-04-26 07:47:45