Saturday, November 21, 2009

Django authentication

How to login a user in Django? There are two ways.

First, "django way", use the function authenticate which returns User model with very necessary attribute backend. This way is good when you log a user in from a form when you know its username and password. But what do to do if needs to log the user in which loaded directly from User model, when you don't know its password (you just have a strongly encoded password's version)?

After a bit of googling I just was able to found a dirty hack - manually append backend attribute to User's object instance. Does anyone know a "django way" to this?

Here's the "Django way" code snippet

user = authenticate(username='user', password='password')
login(request, user)

And here's 'hack':

user = user_info.user
# a dirty hack ;(
user.backend = 'django.contrib.auth.backends.ModelBackend'
login(request, user)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.