Django验证不保持用户登录

时间:2016-08-01 05:07:57

标签: python django authentication web login

我试图通过设计一个基本的登录方案来学习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规则)。

知道发生了什么事吗?

2 个答案:

答案 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)

希望有所帮助:)