尝试扩展django.contrib.auth.views.login时出错

时间:2014-05-09 00:00:52

标签: python django django-authentication

python和django都很新,如果这是一个新手问题,请原谅我。

我正在试图弄清楚如何扩展django.contrib.auth.login中的功能。我要采取的第一步是简单地使用我自己的函数进行登录行为,但不添加任何新行为。我的项目名称是testproject。

在testproject / testproject / urls.py 中:

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

在testproject / auth / views.py 中:

from django.contrib.auth import login

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

但是,这会给我以下错误:

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'

如果我将auth.views.login_user替换为django.contrib.auth.views.login,一切正常。我很难过,我做错了什么?或者我是以错误的方式处理整个问题?

1 个答案:

答案 0 :(得分:1)

您的login_user()是一个观点。因此,它需要返回一个HttpResponse对象。

login()实际接受请求和用户。在视图中查看Django docs for an example如何正确使用login()

参考Django文档和您的示例,您的login_user()视图应如下所示:

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