19

我创建了一个带有自定义验证的自定义表单,如下所示:

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 方法。
触发两个 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,这在我看来有点奇怪。
这是正确的方法吗?

4

1 回答 1

27

你做得很好,但你应该像这样从超级调用加载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
于 2013-04-26T09:18:33.540 回答