所以我一直在研究我的第一个Django项目,我遇到了一个我无法弄清楚的问题。当我运行我的开发服务器时,我收到以下错误:
AttributeError at /register/
'RegistrationForm' object has no attribute 'clean_data'
我很少运气浏览论坛。 这是代码:
观看页面:
def register_page(request):
if request.method=='POST':
form=RegistrationForm(request.POST)
if form.is_valid():
user = User.objects.create_user(
username=form.clean_data['username'],
password=form.clean_data['password1'],
email=form.clean_data['email'])
return HttpResponseRedirect('/')
else:
form = RegistrationForm()
variables = RequestContext(request, {
'form': form})
return render_to_response(
'registration/register.html',
variables
)
表单页面:
class RegistrationForm(forms.Form):
username = forms.CharField(label='Username', max_length=30)
email = forms.EmailField(label='Email')
password1 = forms.CharField(
label='Password (Again)',
widget=forms.PasswordInput()
)
password2 = forms.CharField(
label='Password (Again)',
widget=forms.PasswordInput()
)
def clean_password2(self):
if 'password1' in self.clean_data:
password1 = self.clean_data['password1']
password2 = self.clean_data['password2']
if password1 == password2:
return password2
raise forms.ValidationError('Passwords do not match.')
def clean_username(self):
username = self.clean_data['username']
if not re.search(r'^\w+$', username):
raise forms.ValidationError('Username can only contain'
'alphanumeric characters and the underscore.')
try:
User.objects.get(username=username)
except ObjectDoesNotExist:
return username
raise forms.ValidationError('Username is already taken.')
谢谢, 塞特
答案 0 :(得分:3)
您拼错了属性的名称。请改用cleaned_data
。