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

nassar hayat
nassar hayat
14,509 Points

How do I log user in on signup using django?

I don't know what I am doing wrong here. Looks right to me as far as I can understand.

accounts/views.py
from django.contrib.auth import login
from django.contrib.auth.forms import UserCreationForm
from django.core.urlresolvers import reverse_lazy
from django.views import generic

from . import forms

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

    def form_valid(self, form):
        login(self.request, form.get_user())
        return super().form_valid(form)

1 Answer

Tatiana Vasilevskaya
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Tatiana Vasilevskaya
Python Web Development Techdegree Graduate 28,600 Points

There are some things to think about. Firstly, the docs say

When you’re manually logging a user in, you must successfully authenticate the user with authenticate() before you call login(). authenticate() sets an attribute on the User noting which authentication backend successfully authenticated that user (see the backends documentation for details), and this information is needed later during the login process. An error will be raised if you try to login a user object retrieved from the database directly.

I'm not sure what is the form.get_user() method. However, you definitely need to create the user before you authenticate him and log in. Right now you try to login first and only then create.

nassar hayat
nassar hayat
14,509 Points

Thank you for responding Tatiana.

I thought that form.get_user() gets the user information that is input into the form.