almost 6 years ago

Today, I build a login system in django where the user is not in my server. There is lots of works before I start handling login service in django. After I finish all preliminary works, I try to login by the single username. Here is my code:

user, created = User.objects.get_or_create(username="username")  
auth.login(request, user)

Everything looks good for me. However, it's not work. I  meet the error code:

'User' object has no attribute 'backend'

It is because that the user you obtain from the User model does not contain the information of session backend. Thus, django can not record you login status and it's failed.

After tracing codes in "django.contrib.auth", I find that there is a ModelBackend called "RemoteUserBackend". It is used for cases like mine. According to the document in Django official site, all you have to do is to place the django.contrib.auth.middleware.RemoteUserMiddleware after the django.contrib.auth.middleware.AuthenticationMiddleware in the MIDDLEWARE_CLASSES in settings.py. And then replace AUTHENTICATION_BACKENDS by

AUTHENTICATION_BACKENDS = (  
    'django.contrib.auth.backends.RemoteUserBackend',  
)

You login code will look like this:

user = auth.authenticate(remote_user="username")  
auth.login(request, user)

Then, you can process all other works as it has been.

← Tricks on i18n for Django 1.4 PyBabel 介紹 →
 
comments powered by Disqus