Ali Hassan
Ali Hassan

Reputation: 519

AttribueError:RegistrationForm' object has no attribute 'username'

I am creating user authentication form, on entering data and submitting, I get this error: AttributeError at /register/ 'RegistrationForm' object has no attribute 'username' at ` username=form.username, I have checked all the solutions with the same problem and applied them but no one is solving it(like that is_valid()). how do I get it right? here is the code:

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.')

Upvotes: 1

Views: 2431

Answers (1)

tayfun
tayfun

Reputation: 3135

Its cleaned_data, not clean_data:

username = form.cleaned_data['username']

Do this for other form data as well, like password1 and email.

Some background in the reason for this can be found in Django documentation. Basically, the methods are called clean_fieldname but after cleaning the data is in cleaned_fieldname. Note the distinction.

Upvotes: 3

Related Questions