3

I'm trying to create a simple user registration in Django and I get this error. I've looked it up here on stackoverflow: 'AnonymousUser' object has no attribute 'backend', Django Register Form 'AnonymousUser' object has no attribute 'backend' and tried calling authentication before login. But I keep getting this error.

Can anyone please help me with this?

Here is the traceback

Traceback:
File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in get_response
  114.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Library/Python/2.7/site-packages/django/views/decorators/csrf.py" in wrapped_view
  57.         return view_func(*args, **kwargs)
File "/Users/harisaghadi/Dropbox/Senior Project/Django Tutorials/mysite/meddy1/views.py" in signup_user
  51.           login(request, new_user)
File "/Library/Python/2.7/site-packages/django/contrib/auth/__init__.py" in login
  85.     request.session[BACKEND_SESSION_KEY] = user.backend
File "/Library/Python/2.7/site-packages/django/utils/functional.py" in inner
  214.         return func(self._wrapped, *args)

Exception Type: AttributeError at /meddy1/signup/
Exception Value: 'AnonymousUser' object has no attribute 'backend'

Here is my forms.py

class UserCreationForm(forms.ModelForm):
"""
A form that creates a user, with no privileges, from the given username and
password.
"""
error_messages = {
    'duplicate_username': _("A user with that username already exists."),
    'password_mismatch': _("The two password fields didn't match."),
}
email = forms.EmailField(required=True, widget=forms.TextInput(attrs={'class': 'form-control','placeholder':'Please enter a valid email address so we can reach you.'}))
username = forms.RegexField(label=_("Username"), max_length=30,
    regex=r'^[\w.@+-]+$',
    help_text=_("Required. 30 characters or fewer. Letters, digits and "
                "@/./+/-/_ only."),
    error_messages={
        'invalid': _("This value may contain only letters, numbers and "
                     "@/./+/-/_ characters.")})
password1 = forms.CharField(label=_("Password"),
    widget=forms.PasswordInput)
password2 = forms.CharField(label=_("Password confirmation"),
    widget=forms.PasswordInput,
    help_text=_("Enter the same password as above, for verification."))

class Meta:
    model = User
    fields = ("username",)

def clean_username(self):
    # Since User.username is unique, this check is redundant,
    # but it sets a nicer error message than the ORM. See #13147.
    username = self.cleaned_data["username"]
    try:
        User._default_manager.get(username=username)
    except User.DoesNotExist:
        return username
    raise forms.ValidationError(
        self.error_messages['duplicate_username'],
        code='duplicate_username',
    )

def clean_password2(self):
    password1 = self.cleaned_data.get("password1")
    password2 = self.cleaned_data.get("password2")
    if password1 and password2 and password1 != password2:
        raise forms.ValidationError(
            self.error_messages['password_mismatch'],
            code='password_mismatch',
        )
    return password2

def save(self, commit=True):
    user = super(UserCreationForm, self).save(commit=False)
    user.set_password(self.cleaned_data["password1"])
    if commit:
        user.save()

        userProfile = DoctorSeeker(user=user, name=name, email=email)
        userProfile.save()

    return user

views.py

def index(request):
    return HttpResponse("Welcome to Meddy")

# -------------------- Authentication ----------------------
def signup(request):
    return render(request, 'meddy1/signup.html', {})

@csrf_exempt
def signup_user(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST,request.FILES)
        if form.is_valid():
            new_user = authenticate(username=request.POST['username'],password=request.POST['password1'])
            login(request, new_user)

            return HttpResponseRedirect(reverse('index'))
    else:
        form = UserCreationForm()
    return render(request, "meddy1/signup.html", {'form': form,'usersignup':True})



def login_user(request):
    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(username=username,password=password)
    if user:
        return render(request, 'meddy1/index.html')
    else:
        return HttpResponseRedirect('/')


def logout_user(request):
    logout(request)
    return HttpResponseRedirect('/')

models.py

class DoctorSeeker(models.Model):
    name = models.CharField(max_length=30)
    email = models.EmailField()
    user = models.ForeignKey(User, unique=True)

    def __unicode__(self):
        return u"%s %s" % (self.name, self.email)
Community
  • 1
  • 1
James L.
  • 1,143
  • 22
  • 52
  • You should show the exact traceback, so we know which one of those many views is triggering the error. Note however that your signup_user view seems to be missing a step, ie the one where you actually create the user; and your login_user is also missing a step, the one where you actually log the user in after authenticating. – Daniel Roseman May 19 '14 at 08:02
  • I've added the traceback above. Can you please elaborate on the steps missing ? Thanks – James L. May 19 '14 at 08:39

1 Answers1

2

Since you found the similar posts, i take it, you understand, that your authenticate does not really authenticate anything. It fails for some reason.

I understand that the view you are showing us is trying to accomplish 2 things- create user and log him in? Right? Since its name is signup_user.

Well. You have UserCreationForm, but you do not save it. So you cant really authenticate an user, that does not yet exist in the system. Save your form first, then call authenticate.

Odif Yltsaeb
  • 5,575
  • 12
  • 49
  • 80
  • Thanks a lot. It worked! Can't believe I missed such a trivial thing. – James L. May 21 '14 at 13:29
  • Well you have 2 options now. If the question seems like an embarrassment and you think it will not help anybody else - delete it. If you think it could save someone else some time - accept it. – Odif Yltsaeb May 22 '14 at 06:15