我试图通过设计一个基本的登录方案来学习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
时被重定向到登录视图。仅供参考,我试图通过URL直接访问privatePage
视图,而不是浏览提供的链接(例如,我不确定我是否违反了某些CSRF规则)。
知道发生了什么事吗?
答案 0 :(得分:5)
您尚未实际登录。在使用authenticate
验证用户身份后,您需要登录用户:
from django.contrib.auth import login
user = authenticate(email=email, password=password)
if user is not None:
login(request, user)
login
只应用于已确认存在的用户。
authenticate
做了什么:
验证用户是否是他们声称的用户
它不会执行实际的登录。
答案 1 :(得分:0)
要保持用户登录,必须使用session
方法向用户提供login()
。登录是向用户提供会话和authenticate() verifies that the given credentials corresponds to an existing user model object in database
的过程。导入django内置的登录和身份验证方法from django.contrib.auth import authenticate, login
。然后你的代码看起来像
user =authenticate(email, password)
If user:
login(user, request)
希望有所帮助:)