首页 > 解决方案 > 如何修复“禁止 (403) CSRF 验证失败。请求中止。” django中的错误

问题描述

我在标题中遇到了这个常见错误。我正在虚拟环境文件夹中的 Django 中做一个项目。

设置.py:

        MIDDLEWARE = [
            'django.middleware.security.SecurityMiddleware',
            'django.contrib.sessions.middleware.SessionMiddleware',
            'django.middleware.common.CommonMiddleware',
            'django.middleware.csrf.CsrfViewMiddleware',
            'django.contrib.auth.middleware.AuthenticationMiddleware',
            'django.contrib.messages.middleware.MessageMiddleware',
            'django.middleware.clickjacking.XFrameOptionsMiddleware',
        ]

索引.html:

        {% load static %}
        <!DOCTYPE html>
        <html>

        <head>
            <meta charset="utf-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>Instapic</title>
            <link rel="stylesheet" href="{% static 'assets/bootstrap/css/bootstrap.min.css' %}">
            <link rel="stylesheet" href="{% static 'assets/css/Login-Form-Clean.css' %}">
            <link rel="stylesheet" href="{% static 'assets/css/styles.css' %}">
        </head>

        <body>
            <div class="login-clean">
                <form method="post">
                    {% csrf_token %}

                    <h2 class="sr-only">Login Form</h2>
                    <div class="illustration">
                            <div style="display: none" id="errors" class="well form-error-message"></div>
                            <img src="{% static 'assets/img/logo.jpg' %}">
                    </div>
                    <div class="form-group">
                        <input class="form-control" id="username" type="text" name="username" required="" placeholder="Username" maxlength="20" minlength="4">
                    </div>
                    <div class="form-group">
                        <input class="form-control" id="email" type="email" name="email" required="" placeholder="Email" maxlength="100" minlength="6">
                    </div>
                    <div class="form-group">
                        <input class="form-control" id="password" type="password" name="password" required="" placeholder="Password" maxlength="20" minlength="6">
                    </div>
                    <div class="form-group">
                        <button class="btn btn-primary btn-block" id="go" type="submit">Create Account</button>
                    </div><a href="#" class="forgot">Already got an account? Login here ...</a></form>
            </div>
            <script src="{% static 'assets/js/jquery.min.js' %}"></script>
            <script src="{% static 'assets/bootstrap/js/bootstrap.min.js' %}"></script>
            <script src={% static "assets/js/django-ajax.js" %}></script>
            <script type="text/javascript">
                $(document).ready(function() {
                $('#go').click(function() {
                $.post("ajax-sign-up",
            {
                username: $("#username").val(),
                email: $("#email").val(),
                password: $("#password").val()
            },
            function(data, status){
            if (JSON.parse(data).Status == 'Success') {
                window.location = '/';
            } else {
                $('#errors').html("<span>" + JSON.parse(data).Message + "</span>")
                $('#errors').css('display', 'block')
            }
            });
                return false;
                })
        })
            </script>
        </body>

        </html>

{% csrf_token %}在我的 html 文件中添加了试图解决这个问题 - 没有用。我在网上找到了这个标签示例:

<input type="hidden" id="csrf_token" value='{"csrfmiddlewaretoken": "{{ csrf_token }}"}'>.

不幸的是,我不知道如何使用它来修复我的错误。感谢帮助

标签: pythondjangocsrfdjango-csrfcsrf-token

解决方案


我想,不是发布表单,而是发布值。您需要在执行 $.post() 语句时添加csrfmiddlewaretoken密钥。

未经测试 ,但它可能会解决您的问题

  csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value

或者

 csrfmiddlewaretoken: $('[name=csrfmiddlewaretoken]').val()

通过更新在 HTML 文件中添加这一行

$.post("ajax-sign-up",
    {
        username: $("#username").val(),
        email: $("#email").val(),
        password: $("#password"),
        csrfmiddlewaretoken: $('[name=csrfmiddlewaretoken]').val()
    },

更新的代码是:

    {% load static %}
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Instapic</title>
    <link rel="stylesheet" href="{% static 'assets/bootstrap/css/bootstrap.min.css' %}">
    <link rel="stylesheet" href="{% static 'assets/css/Login-Form-Clean.css' %}">
    <link rel="stylesheet" href="{% static 'assets/css/styles.css' %}">
</head>

<body>
    <div class="login-clean">
        <form method="post">
            {% csrf_token %}

            <h2 class="sr-only">Login Form</h2>
            <div class="illustration">
                    <div style="display: none" id="errors" class="well form-error-message"></div>
                    <img src="{% static 'assets/img/logo.jpg' %}">
            </div>
            <div class="form-group">
                <input class="form-control" id="username" type="text" name="username" required="" placeholder="Username" maxlength="20" minlength="4">
            </div>
            <div class="form-group">
                <input class="form-control" id="email" type="email" name="email" required="" placeholder="Email" maxlength="100" minlength="6">
            </div>
            <div class="form-group">
                <input class="form-control" id="password" type="password" name="password" required="" placeholder="Password" maxlength="20" minlength="6">
            </div>
            <div class="form-group">
                <button class="btn btn-primary btn-block" id="go" type="submit">Create Account</button>
            </div><a href="#" class="forgot">Already got an account? Login here ...</a></form>
    </div>
    <script src="{% static 'assets/js/jquery.min.js' %}"></script>
    <script src="{% static 'assets/bootstrap/js/bootstrap.min.js' %}"></script>
    <script src={% static "assets/js/django-ajax.js" %}></script>
    <script type="text/javascript">
        $(document).ready(function() {
        $('#go').click(function() {
        $.post("ajax-sign-up",
    {
        username: $("#username").val(),
        email: $("#email").val(),
        password: $("#password").val(),
        csrfmiddlewaretoken: $('[name=csrfmiddlewaretoken]').val()
    },
    function(data, status){
    if (JSON.parse(data).Status == 'Success') {
        window.location = '/';
    } else {
        $('#errors').html("<span>" + JSON.parse(data).Message + "</span>")
        $('#errors').css('display', 'block')
    }
    });
        return false;
        })
})
    </script>
</body>

</html>

推荐阅读