Django验证用户无法正常工作

时间:2018-04-19 00:23:48

标签: django python-3.x

我正在冒犯用户并将他重定向到索引页面:

?

这是索引视图:

def sign_user(request):
    username = request.POST['login']
    password = request.POST['pwd']
    user = authenticate(username=username, password=password)
    if user is not None:
        print('success:' + username + " " + password)
        return redirect('/')

结果我得到了:AnonymousUser

我该怎么办?

2 个答案:

答案 0 :(得分:1)

您需要登录用户,例如docs说。

if user is not None:
    login(request, user)

答案 1 :(得分:1)

试试这种方式,

from django.contrib.auth import authenticate, login


def sign_user(request):
    username = request.POST['login']
    password = request.POST['pwd']
    try:
        user = authenticate(username=username, password=password)
        login(request, user)
        return redirect('/')  # login success
    except:
        return redirect('unable to login')