简体   繁体   中英

How to fix “Forbidden (403) CSRF verification failed. Request aborted.” error in django

I'm getting this common error as in the title. I'm doing a project in Django in a virtual environment folder.

setting.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>

I added {% csrf_token %} in my html file trying fix this - didn't work. I've found online this tag example:

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

Unfortunately I don't know how to use it in order to fix my error. Thanks for help

I guess, instead of post a form you are posting values. You need to add csrfmiddlewaretoken key while execute $.post() statement.

This is not Tested but it may be fix your problem

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

or

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

add this line in HTML file by updating

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

updated code is :

    {% 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>

如果您只是发布具有id signup-form的HTML表单的内容(将其添加到<form> ),并且您的表单具有{% csrf_token %} ,则可以使用以下命令在ajax中进行操作:

$.post("ajax-sign-up", $("#signup-form").serialize(), function(data, status){...})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM