Python 尝试扩展django.contrib.auth.views.login时出错
python和django都是新手,如果这是一个新手问题,请原谅 我正试图找出如何扩展django.contrib.auth.login中的功能。我要做的第一步是简单地使用我自己的函数进行登录行为,但不添加任何新行为。我的项目名是testproject 在testproject/testproject/url.py中:Python 尝试扩展django.contrib.auth.views.login时出错,python,django,django-authentication,Python,Django,Django Authentication,python和django都是新手,如果这是一个新手问题,请原谅 我正试图找出如何扩展django.contrib.auth.login中的功能。我要做的第一步是简单地使用我自己的函数进行登录行为,但不添加任何新行为。我的项目名是testproject 在testproject/testproject/url.py中: urlpatterns = patterns('', (r'^login$', 'auth.views.login_user'), ) from django.cont
urlpatterns = patterns('',
(r'^login$', 'auth.views.login_user'),
)
from django.contrib.auth import login
def login_user(request, template_name='registration/login.html'):
return login(request, template_name)
在testproject/auth/views.py中:
urlpatterns = patterns('',
(r'^login$', 'auth.views.login_user'),
)
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\u user
替换为django.contrib.auth.views.login
,一切正常。我被难住了,我做错了什么?还是我用错误的方式解决了整个问题?您的登录用户()
是一个视图。因此,它需要返回一个HttpResponse
对象
login()
实际接收请求和用户。查看如何在视图中正确使用login()
参考Django文档和您的示例,您的login\u 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'})
login()
将请求
和用户
对象作为参数。您提供了一个字符串(模板名称),而不是用户
对象。因此,当代码试图访问用户
对象的属性时出现错误。啊,你的回答让我找到了解决方案。我是从django.contrib.auth
导入登录名的,但我想从django.contrib.auth.views
导入登录名。一旦我纠正了这一点,一切都正常了。不过,还有一个问题,将函数从一个视图导入到另一个视图是否是一种不好的做法?