python - 如何修复 Django 中的 "Forbidden (403) CSRF verification failed. Request aborted."错误

标签 python django csrf django-csrf csrf-token

我遇到了标题中的常见错误。我正在虚拟环境文件夹中的 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',
        ]

index.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 }}"}'> .

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

最佳答案

我想,您不是在发布表单,而是在发布值。 您需要在执行 $.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>

关于python - 如何修复 Django 中的 "Forbidden (403) CSRF verification failed. Request aborted."错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57711477/

相关文章:

python - 匀称的 LineString 交集是否错误?

python - 按索引和列名数组对 Pandas 数据框进行切片

Python lxml 包装元素

python - Django TabularInline 字段在更新内联字段时出错

session - 如何在 Plug 中设置 session 和 CSRF 保护?

javascript - 将 CSRF token 从 Node.js 传递到 Django

python - unicode 字符串列表

django - 如何在给定名称的 Django 中导入模型

node.js - Nodejs 是否有类似于 ruby​​ 的表单助手来生成 CSRF token ?

python - ValueError : Target is multiclass but average ='binary' . 请选择另一个平均设置,[无, 'micro', 'macro', 'weighted']之一