我只是创建并形成让人们注册 forms.py就在这里
from django import forms
from django.conf import settings
from django.contrib.auth import get_user_model
def lowercase_email(email):
"""
Normalize the address by lowercasing the domain part of the email
address.
"""
email = email or ''
try:
email_name, domain_part = email.strip().rsplit('@', 1)
except ValueError:
pass
else:
email = '@'.join([email_name.lower(), domain_part.lower()])
return email
class SignupForm (forms.ModelForm):
username =forms.CharField(
label='username',required=True,max_length=20,min_length=3)
email = forms.EmailField(
label='email',required=True)
password =forms.CharField(
label='password',required=True,max_length=20,min_length=6)
confirm_password= forms.CharField(
label='confirm_password',required=True,max_length=20,min_length=6)
class Meta:
model = get_user_model()
fields = ("username","email","password",)
def clean_email(self):
UserModel = get_user_model()
email=self.cleaned_data["email"]
lower_email=lowercase_email(email)
try:
UserModel._default_manager.get(email=lower_email)
except UserModel.DoesNotExist:
return lower_email
raise forms.ValidationError("this email is already used ")
def clean_password(self):
password = self.cleaned_data["password"]
confirm_password = self.cleaned_data["confirm_password"]
if password != confirm_password:
raise forms.ValidationError("password not same")
return password
这不行,它显示
KeyError at /accounts/signup/
'confirm_password'
Request Method: POST
Request URL: http://localhost:8000/accounts/signup/
Django Version: 1.6
Exception Type: KeyError
Exception Value:
'confirm_password'
Exception Location: C:\pro1\mysns\sns\accounts\forms.py in clean_password, line 50
Python Executable: C:\Python33\python.exe
好了,现在我只需将密码清除方法更改为 def clean_confirm_password(self) 现在它起作用了,
def clean_confirm_password(self):
password = self.cleaned_data["password"]
confirm_password = self.cleaned_data["confirm_password"]
if password != confirm_password:
raise forms.ValidationError("password not same")
return confirm_password
任何人都可以告诉我为什么?感谢
答案 0 :(得分:2)
您应该使用clean
方法检查它们,然后您可以从form.cleaned_data
获取它们。
或者将clean_password
方法更改为:
def clean_password(self):
# use data instead of cleaned_data
password = self.data["password"]
confirm_password = self.data["confirm_password"]
if password != confirm_password:
raise forms.ValidationError("password not same")
return confirm_password
clean_xxx
方法按字段声明的顺序调用,password
在confirm_password
之前调用,因此在调用clean_password
时,form.cleaned_data['confirm_password']
尚未设置