[英]Custom Django Login Form Not Logging Users In
I am trying to create a login page for my webapp.我正在尝试为我的 webapp 创建一个登录页面。 I am able to log users in through the official admin page, but when I use my page the request.user is not logged in.
我可以通过官方管理页面登录用户,但是当我使用我的页面时 request.user 没有登录。
def index(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
return render(request, 'AllocationWebapp/browse.html', {})
else:
print("Invalid login details: {0}, {1}".format(username, password))
return render(request, 'AllocationWebapp/browse.html', {'error': "Invalid login details supplied."})
else:
return render(request, 'AllocationWebapp/login.html', {})
user is being set correctly, but after login request.user is still AnonymousUser and not logged in.用户设置正确,但登录后 request.user 仍然是 AnonymousUser 并且未登录。
I couldn't figure out why this wasn't working using the built in authenticate
and login
functions, so I used this as a workaround.我无法弄清楚为什么使用内置的
authenticate
和login
功能不起作用,所以我使用它作为解决方法。
user = authenticate(username=username, password=password)
request.session['user'] = user.id
Then when I need to know if a user is logged in I just check request.然后,当我需要知道用户是否登录时,我只需检查请求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.