class RegisterForm(forms.Form):
username = forms.CharField(max_length=16, label="Username", required=False)
password = forms.CharField(max_length=100,widget=forms.PasswordInput, required=False)
password2 = forms.CharField(max_length=100,widget=forms.PasswordInput, label="Password Again", required=False)
fullname = forms.CharField(max_length = 100, required=False)
email = forms.EmailField(max_length=100, required=False)
def clean_fullname(self):
if len(self.cleaned_data['fullname']) < 4:
raise forms.ValidationError("Enter your full name.")
def clean_email(self):
if self.cleaned_data['email'].find("@") <= 0:
raise forms.ValidationError("Enter a valid email address.")
def clean_username(self):
if not self.cleaned_data['username']:
raise forms.ValidationError("Enter a username.")
try:
u = User.objects.get(username = self.cleaned_data['username'])
if u:
raise forms.ValidationError("Username is taken.")
except:
pass
def clean_password(self):
if not self.cleaned_data['password']:
raise forms.ValidationError("Enter a password.")
def clean_password2(self):
if not self.cleaned_data['password2']:
raise forms.ValidationError("Enter your password (again)")
def clean(self):
cleaned_data = self.cleaned_data
password = cleaned_data['password'] <<< There is a key error here anytime I submit a form.
password2 = cleaned_data['password2']
if password and password2:
if password != password2:
raise forms.ValidationError("Your passwords do not match.")
return cleaned_data
p
assword = cleaned_data['password']
最佳答案
原因是您的clean_password
函数不返回任何内容。你的密码也不清楚
这是验证的顺序:
清除字段名
清洁的clean_password
和clean_password2
在有效时需要返回一个值。
def clean_password(self):
if not self.cleaned_data['password']:
raise forms.ValidationError("Enter a password.")
return self.cleaned_data['password']
def clean_password2(self):
if not self.cleaned_data['password2']:
raise forms.ValidationError("Enter your password (again)")
return self.cleaned_data['password2']
尽管建议的保存一些击键的格式(特别是在较长的验证中)是。。。
def clean_password2(self):
data = self.cleaned_data['password2']
raise forms.ValidationError("Enter your password (again)")
return data
关于python - 为什么我的Django表单代码这一行出现关键错误?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4466726/