Python Django Authentication Authentication SignUpView

Dillon Ginley
Dillon Ginley
Python Web Development Techdegree Graduate 26,890 Points

why am I not getting the login for this user?

from django.core.urlresolvers import reverse_lazy from django.views import generic from django.contrib.auth.forms import AuthenticationForm, UserCreationForm from django.contrib.auth import authenticate, login from django.http import HttpResponseRedirect

from . import forms

class SignUp(generic.CreateView): form_class = UserCreationForm template_name = 'accounts/signup.html' success_url = reverse_lazy("products:list")

def form_valid(self, form):
    username = "John"
    password = "JohnPW#$#$#"
    user = authenticate(username=username, password=password)
    if user is not None:
        login(self.request, user)
        return HttpResponseRedirect(reverse_lazy("products:list")) 
    return HttpResponseRedirect(reverse_lazy("products:list"))
accounts/views.py
from django.core.urlresolvers import reverse_lazy
from django.views import generic
from django.contrib.auth.forms import AuthenticationForm, UserCreationForm
from django.contrib.auth import authenticate, login
from django.http import HttpResponseRedirect

from . import forms


class SignUp(generic.CreateView):
    form_class = UserCreationForm
    template_name = 'accounts/signup.html'
    success_url = reverse_lazy("products:list")

    def form_valid(self, form):
        username = "John"
        password = "JohnPW#$#$#"
        user = authenticate(username=username, password=password)
        if user is not None:
            login(self.request, user)
            return HttpResponseRedirect(reverse_lazy("products:list")) 
        return HttpResponseRedirect(reverse_lazy("products:list"))

1 Answer

Hi Dillion, I'm more than a little late here but, I figured this would help others in the future. I was able to find a solution from another forum so I thought I'd share it here:

 def form_valid(self, form):
# Stores the result of the validated form as "valid form"
        valid_form = super().form_valid(form)
# Pulls the username and password1 ("the variable name assigned") from the cleaned_data library
        username = form.cleaned_data['username']
        password = form.cleaned_data['password1']
# Authenticated the user with the username and password credentials
        user = authenticate(username=username, password=password)
# Logs the user in 
        login(self.request, user)
        return valid_form
#Don't forget to import "authenticate" and "login"