我为我的 Django 表单编写了一个干净的函数。我将OPTIONAL_PASSWORD_INPUT及OPTIONAL_REPEAT_PASSWORD_INPUT以上定义为密码输入字段:
class addNewMemberForm(SignUpForm):
username = forms.SlugField(required=False,
min_length=MIN_USER_NAME,
max_length=MAX_USER_NAME,
label="Username (optional)",
help_text="If left empty, we will generate a username for you."
)
password = OPTIONAL_PASSWORD_INPUT
password2 = OPTIONAL_REPEAT_PASSWORD_INPUT
def clean(self):
# if user name is filled out, so must be the password field.
if self.data["username"] and not self.data["password"]:
raise forms.ValidationError("If you specify a username, you must specify a password.")
return self.cleaned_data
def __init__(self, *args, **kwargs):
super(SignUpForm, self).__init__(*args, **kwargs)
self.fields.keyOrder = uniqueify(['username', 'email'] + self.fields.keyOrder)
如果我更改if self.data["username"] and not self.data["password"]:为if self.cleaned_data["username"] and not self.cleaned_data["password"]:,Django 会为“用户名”生成一个关键错误。
为什么我可以访问self.data数组的值,但不能self.cleaned_data在我的 clean 函数中访问数组的值?
另一方面,这个问题甚至重要吗?我可以用self.data吗?