How can I programmatically authenticate a user in Django? How can I programmatically authenticate a user in Django? django django

How can I programmatically authenticate a user in Django?


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

from django.contrib.auth import authenticate, loginuser = authenticate(username=username, password=password)if user is not None:    login(request, user)


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/')


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.