Django身份验证未保持用户登录

2024-09-28 12:16:45 发布

您现在位置:Python中文网/ 问答频道 /正文

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

知道发生什么事了吗?在


Tags: and用户form视图getreturnifrequest
2条回答

你还没有真正登录。在使用authenticate验证用户的身份后,您需要登录

from django.contrib.auth import login

user = authenticate(email=email, password=password)
    if user is not None:
        login(request, user)

login只能用于已确认存在的用户。在


authenticate做什么:

verifies a user is who they claim to be

它不执行实际的登录。在

要使用户保持登录状态,必须使用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。然后你的代码看起来像

user =authenticate(email, password)
    If user:
        login(user, request)

希望有帮助:)

相关问题 更多 >

    热门问题