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']
答案 0 :(得分:2)
简短的字面答案是self.cleaned_data是一个没有“密码”作为键的条目的字典。进入下一阶段:
您是否尝试过检查self.cleaned_data
?是仅缺少password
条目还是空白?你在表格上输入了密码吗?如果没有在表单中输入任何内容,您对self.cleaned_data的期望是什么?你的期望是什么基础?
我认为相当怀疑一个名为“clean”的动作动词的方法开始处理名为“cleaning_data”而不是“raw_data”或“uncleaned_data”或“unclean_data”或“not_known_to_be_clean_data”的属性......这是你的想法还是只是Django怪异?
答案 1 :(得分:2)
原因是你的clean_password
函数没有返回任何内容。你的clean_password2
这是验证的顺序:
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