Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Django Authentication Authentication SignUpView

Avraham Shukron
Avraham Shukron
19,609 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,609 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
oliverchou
oliverchou
20,886 Points

I know it's been a while, but I don't quite understand why we have to store the 'super().form_valid(form)' in the 'to_return variable', rather than simply place it after 'return'

I've tried to place it after return and then it couldn't work