Question

Very new to both python and django, please forgive me if this is a newbie question.

I'm trying to figure out how to extend the functionality in django.contrib.auth.login. The first step I'm taking is to simply use my own function for login behavior, but not add any new behavior. My project name is testproject.

In testproject/testproject/urls.py:

urlpatterns = patterns('',
    (r'^login$', 'auth.views.login_user'),
)

In testproject/auth/views.py:

from django.contrib.auth import login

def login_user(request, template_name='registration/login.html'):
    return login(request, template_name)

However, this give me the following error:

Traceback:
File "/usr/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
  111.                         response = callback(request, *callback_args, **callback_kwargs)
File "/home/user/src/testproject/auth/views.py" in login_user
  4.     return login(request, template_name)
File "/usr/lib/python2.7/dist-packages/django/contrib/auth/__init__.py" in login
  72.     request.session[SESSION_KEY] = user.id

Exception Type: AttributeError at /login/
Exception Value: 'str' object has no attribute 'id'

If I replace auth.views.login_user with django.contrib.auth.views.login, everything works fine. I'm stumped, what am I doing incorrectly? Or am I approaching the entire problem in the wrong way?

Was it helpful?

Solution

Your login_user() is a view. Thus, it needs to return an HttpResponse object.

login() actually takes the request and the user. Check out the Django docs for an example of how to use login() correctly in a view.

Referring to the Django docs and your example, your login_user() view should look something like this:

from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.contrib.auth import authenticate, login

def login_user(request, template_name='registration/login.html'):
    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(username=username, password=password)
    if user is not None:
        if user.is_active:
            login(request, user)
            # Redirect to a success page.
            return HttpResponseRedirect('/home/')
        else:
            # Return a 'disabled account' error message
            return render(request, template_name, {'error': 'disabled account'})
    else:
        # Return an 'invalid login' error message.
        return render(request, template_name, {'error': 'invalid login'})
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top