Python Django form cleaning动作异常
我正在覆盖clean方法,但当我这样做时:Python Django form cleaning动作异常,python,django,Python,Django,我正在覆盖clean方法,但当我这样做时: def clean(self): if "post_update_password" in self.data: print(self.cleaned_data) old_password = self.cleaned_data['old_password'] new_password1 = self.cleaned_data['new_password1'] new_passwo
def clean(self):
if "post_update_password" in self.data:
print(self.cleaned_data)
old_password = self.cleaned_data['old_password']
new_password1 = self.cleaned_data['new_password1']
new_password2 = self.cleaned_data['new_password2']
return super().clean()
def clean_new_password2(self):
if "post_update_password" in self.data:
print(self.cleaned_data)
old_password = self.cleaned_data['old_password']
new_password1 = self.cleaned_data['new_password1']
new_password2 = self.cleaned_data['new_password2']
return super().clean()
它返回以下内容:{'old_password':'password,1','new_password1':'a'}
这意味着我无法获取新的\u password2值
当我像这样改变清洁方法时:
def clean(self):
if "post_update_password" in self.data:
print(self.cleaned_data)
old_password = self.cleaned_data['old_password']
new_password1 = self.cleaned_data['new_password1']
new_password2 = self.cleaned_data['new_password2']
return super().clean()
def clean_new_password2(self):
if "post_update_password" in self.data:
print(self.cleaned_data)
old_password = self.cleaned_data['old_password']
new_password1 = self.cleaned_data['new_password1']
new_password2 = self.cleaned_data['new_password2']
return super().clean()
It magicaly工作并返回:
{'old_password': 'Password,1.', 'new_password1': 'PAssssad', 'new_password2': 'a'}
我真的不明白发生了什么事。我知道如何绕过这个问题,但我真的很好奇问题出在哪里。
感谢您的回复编写clean()和clean_fieldname()方法可以满足两种截然不同的需求。
前者允许您独立于其他字段验证给定字段数据的值。后者允许您考虑多个字段的值来验证表单。因此,用第一种或第二种方法编写“验证代码”的结果是不同的,这是正常的
你试过跟随吗
正如您将在本文档中看到的,在字段验证方法末尾调用super.clean()没有多大意义,因为在整个验证过程中都会调用它。此方法(例如clean_new_password_2())的构造应如下所示:
def clean_new_password2(self):
old_value = self.cleaned_data['new_password_2']
new_value = ...
return new_value # this is the value you want for this field
根据我对您的用例的理解,您的代码应该是:
def clean(self):
cleaned_data = super().clean()
... # Do here the validation stuff you want to do with your field values
# and if you changed the values of ones of the field in cleaned_data, do as follows:
return cleaned_data # you can even return whatever you want
# If you changed nothing, you don't need a return statement
在函数中调用super().clean()
notclean\u new\u密码2
,因此它返回一个字典。