我正在尝试使用 django.contrib.auth.login 将用户 ID 存储在 session 中。但它没有按预期工作。
我收到错误消息 login() takes exactly 1 argument (2 given)
使用 login(user) 我得到 AttributeError at/login/User' object has no attribute 'method'
我正在使用稍微修改过的示例表单 http://docs.djangoproject.com/en/dev/topics/auth/ :
from django.shortcuts import render_to_response
from django.contrib.auth import authenticate, login
def login(request):
msg = []
if request.method == 'POST':
username = request.POST['u']
password = request.POST['p']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
msg.append("login successful")
else:
msg.append("disabled account")
else:
msg.append("invalid login")
return render_to_response('login.html', {'errors': msg})
login.html 没有什么特别之处:
<html>
<head>
<title></title>
</head>
<body>
<form action="/login/" method="post">
Login: <input type="text" name="u">
<br/>
Password: <input type="password" name="p">
<input type="submit" value="Login">
</form>
{% if errors %}
<ul>
{% for error in errors %}
<li>{{ error }}</li>
{% endfor %}
</ul>
{% endif %}
</body>
</html>
有没有人知道如何让 login() 工作。
最佳答案
您的 View 函数也称为 login
,对 login(request, user)
的调用最终被解释为试图递归调用此函数:
def login(request):
...
login(request, user)
为避免它重命名您的 View 函数或以某种不同的方式引用 django.contrib.auth
中的 login
。例如,您可以更改导入以重命名登录功能:
from django.contrib.auth import login as auth_login
...
auth_login(request, user)
关于Django "login() takes exactly 1 argument (2 given)"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1134476/