How to automatically log in users in with Django

Alice Ridgway
1 min readOct 10, 2020

Django does not automatically log in users after signing in, but achieving this functionality only takes a few extra lines of code.

Notes

I’m using Class-based Views. To automatically log in a user, we have to override the form_valid() method of the CreateView class. The form_valid() method is the last block of code to be run before redirecting the user to the success_url.

Django contrib auth provides two functions: authenticate and login. We can call these methods to log a user in without displaying a login form.

The Django source code is a good place to find out more about the authenticate and login methods:

For more Django tutorials, including how to learn Django for free, check out my website.

--

--