How to automatically log in users in with Django

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:

Full-stack developer and Django enthusiast. When I can’t find Django tutorials, I write them. https://twitter.com/alcampk