gpt4 book ai didi

python - 如何使用django登录

转载 作者:太空宇宙 更新时间:2023-11-04 03:11:51 25 4
gpt4 key购买 nike

我有以下代码,但收到一条错误消息:“用户对象没有属性 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() 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 教程,它应该可以正常工作:

https://docs.djangoproject.com/en/1.9/topics/auth/default/#how-to-log-a-user-in

最佳答案

发生的事情是您尝试从 django.contrib.auth 调用 login,但您还定义了自己的函数 login(),你这里有一种名称冲突。

您应该将其重命名为其他名称,例如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

如果你不想重命名,你可以用不同的名字导入 Django 的 login,例如

from django.contrib.auth import login as auth_login

# Then use auth_login(user) in your code

关于python - 如何使用django登录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37751775/

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