0

我正在使用本教程尝试创建一个 django 登录应用程序(超级简单的东西......)

这是我在模板中最终得到的代码 ( index.html)

<div id="login-box">
            {{ state }}
            <form class="login-widgets" action="/login/" method="post">
                {% if next %}
                <input class="login-widgets-text" type="hidden" name="next" value="{{ next }}" />
                {% endif %}
                Username :
                <input class="login-widgets-text" type="text" name="username" value="{{ username}}" /><br />
                Password :
                <input type="password" name="password" value="" /><br />
                <input class="login-button" type="submit" value="Log In" />
            </form>
            <!--<div class="login-widgets">
                <p>Username : ___________</p>
                <p>Password : ___________</p>
            </div>-->
      </div>

这就是教程告诉我添加到我的应用程序views.py页面的内容:

def login_user(request):
    state = "Please log in below..."
    username = password = ''
    if request.POST:
        username = request.POST.get('username')
        password = request.POST.get('password')

        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                state = "You're successfully logged in!"
            else:
                state = "Your account is not active, please contact the site admin."
        else:
            state = "Your username and/or password were incorrect."

    return render_to_response('index.html',{'state':state, 'username': username})

我完全按照教程和 django 文档中的描述设置了我的测试数据库,但我的登录仍然在浏览器中收到此错误:

Forbidden (403)
CSRF verification failed. Request aborted.

我不明白 CSRF 验证是什么意思 - 在我settings.py的 MIDDLEWARE_CLASSES 中,我设置了以下内容:

MIDDLEWARE_CLASSES = ('django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django. contrib.messages.middleware.MessageMiddleware', # 取消注释下一行以获得简单的点击劫持保护:# 'django.middleware.clickjacking.XFrameOptionsMiddleware', )

但我不确定如何验证 CSRF 并验证登录。据我所知,数据库超级用户和上面的代码看起来是正确的,只是我不知道如何添加CSRF验证。非常感谢你的帮助!

4

1 回答 1

2

{% csrf_token %}在表单中添加。它将被一个带有键的隐藏输入所取代。

一步一步的文档

概念解释

于 2013-07-23T22:10:37.830 回答