Django“ login()仅接受1个参数(给定2)”错误

我尝试使用 django.Contrib.auth.login 在会话中存储用户的 ID。但它并没有像预期的那样起作用。

我得到错误 Login ()只有1个参数(给定2)

通过登录(用户) ,我得到了 在/login/User’对象上的 AttributeError 没有属性“ 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})

登录没有什么特别之处。 .html:

<html>
<head>
<title></title>
</head>
<body>
<form action="/login/" method="post">
Login:&nbsp; <input type="text" name="u">
<br/>
Password:&nbsp; <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 ()工作吗。

41690 次浏览

Your view function is also called login, and the call to login(request, user) ends up being interpreted as a attempt to call this function recursively:

def login(request):
...
login(request, user)

To avoid it rename your view function or refer to the login from django.contrib.auth in some different way. You could for example change the import to rename the login function:

from django.contrib.auth import login as auth_login


...
auth_login(request, user)

One possible fix:

from django.contrib import auth


def login(request):
# ....
auth.login(request, user)
# ...

Now your view name doesn't overwrite django's view name.

Another way:

from django.contrib.auth import login as auth_login

then call auth_login(request, user) instead of login(request, user).