如何使用Django登录 [英] how to use django login
问题描述
我有以下代码,但出现错误消息:用户对象没有属性POST"
I have the following code and I get an error saying: "the User object has no attribute POST"
def login (request):
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(user)
return render(request, 'base_in/base_in.html', {})
else:
return render(request, 'signupapp/error.html', {'message':'the acount is not active'})
else:
return render(request, 'signupapp/error.html', {'message':'username and password is incorrect'})
我也尝试了这段代码,并遇到另一个错误:"login()接受1个位置参数,但给出了2个位置"
I also tried this code and got another error: "login() takes 1 positional argument but 2 were given"
def login (request):
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(user)
return render(request, 'base_in/base_in.html', {})
else:
return render(request, 'signupapp/error.html', {'message':'the acount is not active'})
else:
return render(request, 'signupapp/error.html', {'message':'username and password is incorrect'})
我做错了什么?根据django教程,它应该可以正常工作:
What am I doing wrong? Based on django tutorials it should work properly:
https://docs.djangoproject.com/zh-CN/1.9/topics/auth/default/#how-to-log-a-user-in
推荐答案
发生了什么事,您尝试从django.contrib.auth 调用的
login
.还定义了自己的名为 login()
的函数,您在这里会遇到一种名称冲突.
What happened is you try to call login
of from django.contrib.auth
, but you are also defining your own function called login()
, you have a kind of name conflict here.
您应该将其重命名为其他名称,例如 login_view()
You should rename that to something else, e.g. login_view()
from django.contrib.auth import authenticate, login
def login_view(request): # If you call it login,
# you get conflict with login imported aove
# The rest of your code here
# now if you call login(user), it will use the correct one,
# i.e. the one imported from django.contrib.auth
如果您不想重命名,则可以使用其他名称(例如
If you prefer not to rename, you can import Django's login
under a different name, e.g.
from django.contrib.auth import login as auth_login
# Then use auth_login(user) in your code
这篇关于如何使用Django登录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!