19

关于模型表单上的 clean 方法,我有两个问题。这是我的例子:

class AddProfileForm(ModelForm):
        ...
        password = forms.CharField(max_length=30,widget=forms.PasswordInput(attrs={'class':'form2'}))
        password_verify = forms.CharField(max_length=30,widget=forms.PasswordInput(attrs={'class':'form2'}), label='Retype password')
        ...

        class Meta:
            model = UserModel
            fields=("username", "password", "password_verify", "first_name", "last_name", "date_of_birth", "biography", "contacts", )

        #called on validation of the form
        def clean(self):
            #run the standard clean method first
            cleaned_data=super(AddProfileForm, self).clean()
            password = cleaned_data.get("password")
            password_verify = cleaned_data.get("password_verify")

            #check if passwords are entered and match
            if password and password_verify and password==password_verify:
                print "pwd ok"
            else:
                raise forms.ValidationError("Passwords do not match!")

            #always return the cleaned data
            return cleaned_data
  1. 我应该总是调用标准清洁方法吗?

    cleaned_data=super(AddProfileForm, self).clean()
    
  2. 我应该总是返回cleaned_data 变量吗?

    return cleaned_data
    
4

1 回答 1

22

对于 1,是的,如果您想使用父类的验证器。请参阅文档上的此说明。

警告

ModelForm.clean() 方法设置一个标志,使模型验证步骤验证标记为 unique、unique_together 或 unique_for_date|month|year 的模型字段的唯一性。

如果您想覆盖 clean() 方法并维护此验证,则必须调用父类的 clean() 方法。

对于 2,是的,如果数据正确验证。否则引发验证错误。

于 2013-08-22T04:07:50.023 回答