request.user总是返回AnonymousUser - Django

时间:2017-06-20 05:28:10

标签: django

我有一个应用authy_me并写了一个自定义网址

url(r'^login/$', authy_views.log_me_in, name="login")

log_me_in视图包含以下内容:

from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth.views import login as auth_login
def log_me_in(request):

    if request.user.is_staff and not has_2fa(request):
        logger.info('is staff but does not have 2FA, redirecting to Authy account creator')
        return redirect('admin/authy_me/authenticatormodel/')
    elif request.user.is_staff and has_2fa(request):
        logger.info("is staff and 2FA enabled redirecting to Authy verification")
        return redirect('2fa')
    elif not request.user.is_staff and not has_2fa(request):
        logger.info('is not staff and does not have 2FA')

    defaults = {
        'authentication_form': AuthenticationForm,
        'template_name': 'login.html',
    }
    return auth_login(request, **defaults)

当我打印request.user时,我将其视为AnonymousUser,但事实是它正在工作,我没有改变任何东西!我不确定问题是什么。

帮助!!

1 个答案:

答案 0 :(得分:1)

在将请求传递给auth_login(),

之前,您需要对用户进行身份验证
from django.contrib.auth import authenticate

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

检查,如果用户是有效用户,

if not user:
    return False

现在,您可以将请求传递给auth_login()

希望这有帮助