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)

1 Answer

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)```