Python Django Authentication Authentication SignUpView

carlaos91
carlaos91
Python Web Development Techdegree Student 22,931 Points

SignUp view problem

Hi all,

I am getting a "Bummer: Try again!" error. I can't spot the error.

accounts/views.py
from django.core.urlresolvers import reverse_lazy
from django.contrib.auth import authenticate, login
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):
        saved_form = super().form_valid(form)
        usr = form.cleaned_data['username'] 
        pswd = form.cleaned_data['password2'] # use confirmation field
        user = authenticate(username=usr, password=pswd)
        if user is not None:
            if user.is_active:
                login(self.request, user)
        return saved_form

1 Answer

Owen Orsetti
Owen Orsetti
19,089 Points

You issue might be in your if conditions? I'm not sure as I didn't try to do it this way, but maybe one of those if conditions is failing, like for example the is_active attribute, which would prevent the user from being logged in.

The code I used for the challenge assumes that if the registration form is valid then the user is also valid and simply logs them in directly.

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