Python Django Authentication Authentication SignUpView

Avraham Shukron
Avraham Shukron
19,608 Points

Django Authentication: Login automatically after signup

I'm trying to solve the 2nd task in the challenge, but I can't get it right.

As I understand, I need to override form_valid, and in it call login with the newly created user. That does not work.

Reading the documentation is sounds like I have to authenticate the user before calling login. I tried doing that, with the username and the password from form.cleaned_data, but that didn't help either.

The real problem for me is that I don't get to see the actual error message. All I get is the generic "Task 1 is no longer passing" message which does not help at all to understand whats wrong.

accounts/views.py
from django.contrib.auth import login, authenticate
from django.core.urlresolvers import reverse_lazy
from django.views import generic

from . import forms


class SignUp(generic.CreateView):
    form_class = forms.UserCreateForm
    template_name = 'accounts/signup.html'
    success_url = reverse_lazy("products:list")

    def form_valid(self, form):
        to_return = super().form_valid(form)
        login(self.request, self.object)
        return to_return

1 Answer

Avraham Shukron
Avraham Shukron
19,608 Points

Well after digging deeper into UserCreationForm I found two things:

  1. You do need to authenticate before login
  2. The password field in the UserCreationForm is called password1 and not password

So the correct method would look like:

def form_valid(self, form):
    to_return = super().form_valid(form)
    user = authenticate(
        username=form.cleaned_data["username"],
        password=form.cleaned_data["password1"],
    )
    login(self.request, user)
    return to_return