我正在覆盖干净的方法,但是当我这样做时:
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()
它返回以下内容:{'old_password': 'Password,1.', 'new_password1': 'a'}
这意味着我无法获取该new_password2值。
当我这样更改清洁方法时:
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': 'PAssssad', 'new_password2': 'a'}
我真的不明白发生了什么。我知道如何绕过此问题,但我真的很好奇问题出在哪里。 感谢您的答复
答案 0 :(得分:0)
编写 clean()和 clean_fieldname()方法满足两种截然不同的需求。 前者可让您独立于其他人来验证给定字段数据的值。后者允许您通过考虑几个字段的值来验证表单。因此,在第一种方法或第二种方法中编写“验证码”的结果通常是不同的。
您是否尝试遵循Django documentation about this subject?
正如您将在本文档中看到的那样,在字段验证方法末尾调用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