gpt4 book ai didi

django - 模型形式:覆盖清洁方法

转载 作者:行者123 更新时间:2023-12-03 23:44:14 25 4
gpt4 key购买 nike

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

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
  • 我应该总是调用标准的干净方法吗?
    cleaned_data=super(AddProfileForm, self).clean()
  • 我应该总是返回cleaned_data 变量吗?
    return cleaned_data
  • 最佳答案

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

    Warning

    The ModelForm.clean() method sets a flag that makes the model validation step validate the uniqueness of model fields that are marked as unique, unique_together or unique_for_date|month|year.

    If you would like to override the clean() method and maintain this validation, you must call the parent class’s clean() method.



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

    关于django - 模型形式:覆盖清洁方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18371457/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com