Python Django实用项目-第168页
在第168页,有两段代码:Python Django实用项目-第168页,python,django,project,Python,Django,Project,在第168页,有两段代码: def clean_password2(self): if self.cleaned_data['password1'] != self.cleaned_data['password2']: raise forms.ValidationError("You must type the same password each time") return self.cleaned_data['password2'] def clean(self):
def clean_password2(self):
if self.cleaned_data['password1'] != self.cleaned_data['password2']:
raise forms.ValidationError("You must type the same password each time")
return self.cleaned_data['password2']
def clean(self):
if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
if self.cleaned_data['password1'] != self.cleaned_data['password2']:
raise forms.ValidationError("You must type the same password each time")
return self.cleaned_data
在第二种情况下,代码检查“password1”和“password2”是否有任何值。在第一种情况下,没有这样的检查。为什么?清除\u password2方法正在清除字段,在本例中为password2字段。() 在单个字段验证之后调用
clean
方法。这是根据文档进行多字段验证的好地方
阅读更多。在
clean\u password2
中,您正在验证password2
字段,因此您可以确定该字段存在于该表单上,而无需在self.cleaned\u data
中检查是否存在该字段。然而,这并不意味着他们不能检查密码1的eixstence
clean
方法正在验证整个表单,并且无法保证存在的内容。非常感谢你们两位。我正在寻找一个代码,允许用户订阅,只有当他们被邀请(有点像在Quora)。我在哪里能找到?谢谢