Django 的行为就像用户已登录但不是

Django acts like user is logged in but isn't

我的 Django 项目中有一个 AJAX 登录名。 ajax_login view 获取 POST、验证用户和 returns JsonResponse。一切似乎都正常,但用户实际上并未登录。

奇怪的是,在视图中,我正在测试用户是否已登录,他们是。

VIEW

@csrf_exempt
def ajax_login_(request):
    username = request.POST.get('username')
    password = request.POST.get('password')

    user = authenticate(username=username,password=password)

    if user:
        if user.is_authenticated():
            print 'IS LOGGED IN' #THIS IS BEING PRINTED INTO CONSOLE SO USER IS LOGGED IN
            return JsonResponse({'status':0})

    return JsonResponse({'status':1})

AJAX

$(document).ready(function () {
    $('.login-form').find('.submitButton').click(function (e) {
        var next = $(this).closest('.login-form').find('input[name="next"]').val();
        var password = $(this).closest('.login-form').find('#id_password').val();
        var username =$(this).closest('.login-form').find('#id_username').val();
        e.preventDefault();
        var errors = 0;
        if (username == '') {
            $('#id_username_required').show();
            errors += 1;
        } else {
            $('#id_username_required').hide();
        }
        if (password == '') {
            $('#id_password_required').show();
            errors += 1;
        } else {
            $('#id_password_required').hide();
        }

        if (errors == 0) {
            $.ajax({
                url: '/ajax/login/',
                type: 'post',
                data: {
                    'password': password,
                    'username': username,
                },
                success: function (data) {
                    if (data.status == 0) {
                        window.location.reload();
                    } else {
                        $('.login-modal-credentials-incorrect').show();
                        return false;
                    }
                }
            });
        }
    })
});

想不通哪里出了问题。它突然停止工作了。

我认为,问题出在您的 js 代码中,您正在重新加载当前页面。而不是那样,我相信,如果用户已成功通过身份验证,您必须将登录 page/home 页面重定向到用户。

例如

$.ajax({
            url: '/ajax/login/',
            type: 'post',
            data: {
                'password': password,
                'username': username,
            },
            success: function (data) {
                if (data.status == 0) {
                    window.location = "http://yourhost/landing-url"
                } else {
                    $('.login-modal-credentials-incorrect').show();
                    return false;
                }
            }
        });

您忘记在 authenticate() 之后调用 login()

from django.contrib.auth import authenticate, login

def ajax_login_(request):
    ...
    user = authenticate(username=username, password=password)
    if user is not None:
        login(request, user)

有关详细信息,请参阅 how to log a user in 上的文档。

问题和往常一样非常简单。我不小心删除了 authenticate 之后的 login(request,user) 行,所以用户已经通过身份验证但没有登录。