Django 即使在登录后也重定向到登录页面

Django redirects to login page even after logging in

这是views.py的内容:


    @login_required
    def home_page(请求):
        return HttpResponse("hello " + str(request.user))

    定义登录(请求):
        return 渲染(请求,'login.html')

    def 验证(请求):
        你 = request.POST['username']
        p = request.POST['password']
        user = authenticate(用户名=u, 密码=p)
        如果用户不是无:
            如果 user.is_active:
                登录(请求)
                打印("logged in")
                return HttpResponseRedirect('/')
        别的:
            return HttpResponseRedirect('/accounts/login/')

在转到“/”时,我被重定向到“/accounts/login”,这会将我带到登录页面。在我输入用户名和密码后,在 "Verify" 中打印语句 printd "logged in" 到终端。

到目前为止一切顺利。现在,我没有被重定向到“/”,而是再次被重定向到“/accounts/login”,并且显示页面以再次输入用户名和密码。为什么?


    [09/Jan/201510:50:14]"GET / HTTP/1.1"302 0
    [09/Jan/2015 10:50:14] "GET /accounts/login/?next=/ HTTP/1.1" 200 250
    登录
    [09/Jan/201510:50:19]"POST /accounts/verify/ HTTP/1.1"302 0
    [09/Jan/201510:50:19]"GET / HTTP/1.1"302 0
    [09/Jan/2015 10:50:19] "GET /accounts/login/?next=/ HTTP/1.1" 200 250

您忘记了 login 的第二个参数,即用户对象。这导致登录失败,因此当您重定向到首页(有 @login_required)时,您将被发送回登录表单 "log in again"。看看the docs.

编辑:您正在导入 django.contrib.auth.login 并且在您的脚本中有一个名为 login 的函数——这些名称与您本地定义的函数 "takes over" 冲突。您应该重命名您的本地函数(我在下面称之为 login_view),或者将登录函数导入为 qualified/different 名称(例如,您可以执行 from django.contrib.auth import authenticate, login as login_user)

from django.contrib.auth import authenticate, login

@login_required
def home_page(request):
    return HttpResponse("hello " + str(request.user))

def login_view(request):
    return render(request, 'login.html')

def verify(request):
    u = request.POST['username']
    p = request.POST['password']
    user = authenticate(username=u, password=p)
    if user is not None:
        if user.is_active:
            # You need to call `login` with `request` AND `user`
            login(request, user)
            print("logged in")
            return HttpResponseRedirect('/')
    else:
        return HttpResponseRedirect('/accounts/login/')