gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 18:43:10 26 4
gpt4 key购买 nike

对 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,一切正常。我很难过,我做错了什么?还是我以错误的方式解决了整个问题?

最佳答案

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

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

引用 Django 文档和您的示例,您的 login_user() View 应如下所示:

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

关于python - 尝试扩展 django.contrib.auth.views.login 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23554648/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com