43

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?

3 Answers 3

68

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) 
Sign up to request clarification or add additional context in comments.

6 Comments

Re your revision comment: PEP 8 recommends omitting spaces around = in keyword arguments, but of course you're free to do whatever you want.
@icktoofay I'm well aware of what PEP 8 recommends. (It's not a good recommendation)
@CatPlusPlus You really think its a bad recommendation? Thats odd of you.
@jdg do you have a substantial argument, or did I miss the memo about how we are now supposed to qualify users instead of posts on SO? :/
Itendtothinkspaceshelpreadabilityingeneral.Letpeopleusewhitespacethewaytheywant.ThisisprobablythebiggestthingthatbugsmeaboutPython
|
7

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

Comments

2

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.