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

User Creation Form View override to login user

So, I'm trying to login the user after creating the said user. I've tried the code attached and also a couple configurations using the super function, but I'm not seeming to be able to nail down how to do this.

Does anyone have suggestions on what I'm doing wrong. The error that I'm getting is "It looks like Task 1 is no longer passing", which I've often found means that there's an error getting raised.

Any help is much appreciated.

accounts/views.py
from django.contrib.auth import authenticate, 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):
        self.object = form.save()
        login(self.request, self.object)
        return HttpResponseRedirect(self.get_success_url())

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,441 Points

Your started in the right direction. No need to do an http redirect as the success_url will handle that. The method form_valid needs to return a valid form.

The necessary steps are:

  • call super form to validate for, hold result to return later
    res = super().form_valid(form)
  • Get username and password1 from the form.cleaned_data dictionary
  • authenticate user with username and password1 and assign to user
  • login user using login(self.request, user)
  • return res from above