How can I programmatically authenticate a user in Django?

Question:

How can I log-in the user programmatically in Django? I have the username and password of the User. Is there a method that let’s me log him in?

Asked By: Mridang Agarwalla

||

Answers:

There is no other way than “programmatically”. Of course, this is documented.

from django.contrib.auth import authenticate, login

user = authenticate(username=username, password=password)
if user is not None:
    login(request, user)
Answered By: Cat Plus Plus

Alsways be careful when programmatically logging users in, you might get the error ยดuser has no attribute "backend". You have to set the backend too if that has no happened previously. Project that uses this and some sample code:

def splash_register(request):
  if request.session.get('beta'):

    if request.method=='POST':
        userform=MyUserCreationForm(request.POST)
        if userform.is_valid():
            #username of <30 char is required by Django User model.  I'm storing username as a hash of user email 

            user=userform.save(commit=False)
            user.username=hash(user.email)
            user.backend='django.contrib.auth.backends.ModelBackend'
            user.save()


            username=user.username
            password=str(userform.cleaned_data['password'])
            auth.login(request, user)
            request.session['first_visit']=True
            return HttpResponseRedirect("/")
        else:
            userform=MyUserCreationForm(request.POST)
            return render_to_response("website/splash_register.html", {'userform':userform}, context_instance=RequestContext(request))
    return render_to_response("website/splash_register.html", context_instance=RequestContext(request))     
else:
    return HttpResponseRedirect('/splash/')
Answered By: Sebastian Wozny

The accepted answer definitely works but, I prefer to use the Django built in auth forms, like django.contrib.auth.forms.AuthenticationForm

Here is a snippet that shows the important part

form = AuthenticationForm(request, data=request.POST)
if form.is_valid():
    try:
        form.clean()
    except ValidationError:
        # handle error

    login(request, form.get_user())

The major difference in this approach is that AuthenticationForm.clean method calls authentication function for you and checks User.is_active for you as well.

Answered By: SciGuyMcQ
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.