我试图通过设计一个基本的登录场景来学习Django的身份验证系统。我的视图被设置为这样一个视图logIn
要么接收用户的凭据(并打印登录的成功/失败),要么呈现一个登录表单。在
第二个视图privatePage
,被设计为用户是否实际登录的健全性检查。代码如下:
views.py
:@login_required(login_url='/logIn')
def privatePage(request):
return HttpResponse("You're viewing a private page")
@csrf_exempt
def logIn(request):
if request.method == "POST" and \
request.POST.get('email') and \
request.POST.get('password'):
user = authenticate(username=request.POST['email'],
password=request.POST['password'])
return HttpResponse('Valid login' if user is not None else 'Invalid login')
# render login form
return HttpResponse("<form>...</form>")
我发现在通过logIn
视图成功登录后,当我试图访问privatePage
时,我仍然被重定向到login视图。仅供参考,我尝试通过URL直接访问privatePage
视图,而不是通过提供的链接导航(例如,我不确定是否违反了CSRF规则)。在
知道发生什么事了吗?在
你还没有真正登录。在使用
authenticate
验证用户的身份后,您需要登录:login
只能用于已确认存在的用户。在authenticate
做什么:它不执行实际的登录。在
要使用户保持登录状态,必须使用
login()
方法向用户提供session
。登录是向用户提供会话和authenticate() verifies that the given credentials corresponds to an existing user model object in database
的过程。导入django的内置登录和身份验证方法from django.contrib.auth import authenticate, login
。然后你的代码看起来像希望有帮助:)
相关问题 更多 >
编程相关推荐