我正在创建用户身份验证表单,在输入数据和提交时,我收到此错误: / register /的AttributeError 'RegistrationForm'对象没有属性'username' 在`username = form.username, 我已经检查了所有具有相同问题的解决方案并应用了它们,但没有人解决它(就像is_valid())。我怎么做对的?这是代码:
from django.http import HttpResponse
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('/register/success/')
else:
form = RegistrationForm()
variables = RequestContext(request, {
'form': form})
return render_to_response(
'registration/register.html',
variables)
def logout_page(request):
logout(request)
return HttpResponseRedirect('/')
def main_page(request):
return render_to_response(
'main_page.html', RequestContext(request))
def user_page(request, username):
try:
user = User.objects.get(username=username)
except:
raise Http404('Requested user not found.')
bookmarks = user.bookmark_set.all()
template = get_template('user_page.html')
variables = RequestContext(request, {
'username': username,
'bookmarks': bookmarks
})
output = template.render(variables)
return HttpResponse(output)
forms.py
import re
class RegistrationForm(forms.Form):
username = forms.CharField(label='Username', max_length=30)
email = forms.EmailField(label='Email')
password1 = forms.CharField(
label='Password',
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 .')
try:
User.objects.get(username=username)
except ObjectDoesNotExist:
return username
raise forms.ValidationError('Username is already taken.')
答案 0 :(得分:3)
其cleaned_data
,而不是clean_data
:
username = form.cleaned_data['username']
也可以为其他表单数据执行此操作,例如password1和email。
可以在Django documentation中找到原因的一些背景知识。基本上,这些方法称为clean_fieldname
,但在清理后数据位于cleaned_fieldname
。注意区别。