There are several points during the pieces of a Django app’s lifecycle where you’d like to log in a user without going through the standard login views. These are situations when the user has authenticated their identity in some other way, for example:
- User just successfully signed up. There’s no reason to ask them to re-enter the credentials they just set up.
- User just reset their password.
The official documentation isn’t super clear on how to do it, but it turns out its incredibly easy:
from django.contrib.auth import login user.backend = 'django.contrib.auth.backends.ModelBackend' login(request, user)
The backend is used by the auth system later on in the process.
2 comments so far...
You saved my life! Thank you, you’r a god send.
Another nice way of doing it is to call authenticate first:
from django.contrib.auth import login, authenticate
# auto login new registered user
username = request.POST['username']
password = request.POST['password1']
user = authenticate(username=username, password=password)
login(request, user)
leave a reply