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

Nathan Magyar
Nathan Magyar
11,332 Points

Change the SignUp view so that, when the form is valid, the user gets logged in.

I'm trying to change the SignUp view so that, when the form is valid, the user gets logged in. I'm not getting a descriptive error so debugging is proving difficult. Is there some other function I'm not importing that I should be?

accounts/views.py
from django.contrib.auth import login
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):
        login(self.request, form.get_user())
        return super().form_valid(form)

2 Answers

Nathan Magyar
Nathan Magyar
11,332 Points

A bit of Google work led me to Stack Overflow, where I realized there are a number of other steps and other functions involved:

from django.core.urlresolvers import reverse_lazy
from django.http import HttpResponseRedirect
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):
        #save the new user first
        form.save()
        #get the username and password
        username = self.request.POST['username']
        password = self.request.POST['password1']
        #authenticate user then login
        user = authenticate(username=username, password=password)
        login(self.request, user)
        return HttpResponseRedirect(self.success_url)```

This answer doesn't work, like usual. This is a treehouse problem and it causes students to needlessly spend effort trying to figure out what makes it right given the OUTDATED materials.