Feb 26

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...

  • Niklas Said on September 1st, 2009 at 5:15 am:

    You saved my life! Thank you, you’r a god send.

  • David Thompson Said on March 26th, 2010 at 8:40 am:

    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

Spam Protection by WP-SpamFree