Django tip: Automatic logins

In the Django documentation we see the following:

When you're manually logging a user in, you must call authenticate() before you call login().

That's all really nice, because it makes sure that all your authentication backends are tried out; but if you want a really quick remedy for getting the job done, then you'll need to set the user.backend property to the specific backend that authenticated the user. Beware that the Django developers can change these requirements. I wanted this to avoid writing my own backend, so I did this to log users in via a special view accepting a hash from the URL (from an e-mail that had a link that'd automatically log a user in). This could also become useful if you want to become a different user.

 def get_hash(s):  
    import hashlib  
    m = hashlib.md5()  
    m.update(str(s) + settings.LOGIN_SECRET)  
    return str(m.hexdigest())





def auto_login(request, user_id, secret):

    user = get_object_or_404(User, id=user_id)

    if not secret == get_hash(str(user_id)):  
        raise Http404()

    user.backend = "django.contrib.auth.backends.ModelBackend"  
    login(request, user)

    return HttpResponseRedirect(reverse('frontpage'))

BEWARE!
I strongly suggest that you don't log any superusers in this way. You could add a conditional statement not user.is_superuser or similar.