所以我正在做一个django项目,通过关注youtube的视频。我得到了这个错误:
"Forbidden (403) CSRF verification failed. Request aborted."每次我在我的sign-up.html文件中提交任何数据时。然后我意识到我没有正确地配置ajax。所以我在网上搜索,看到了ajax的django文档。我对我的html代码做了一些修改。但是,这并没有解决我的问题。我仍然得到相同的结果。这里我的错误是什么。我在配置ajax时犯了什么错误吗?
"assets/js/django-ajax.js“这是我保存jquery文件的位置。
自从我陷入这个问题已经有一段时间了。
谢谢您抽时间见我
我的sign-up.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>我的ajax配置:
    // using jQuery
    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    var csrftoken = getCookie('csrftoken');
    function sameOrigin(url) {
        // test that a given url is a same-origin URL
        // url could be relative or scheme relative or absolute
        var host = document.location.host; // host + port
        var protocol = document.location.protocol;
        var sr_origin = '//' + host;
        var origin = protocol + sr_origin;
        // Allow absolute or scheme relative URLs to same origin
        return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
            (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
            // or any other URL that isn't scheme relative or absolute i.e relative.
            !(/^(\/\/|http:|https:).*/.test(url));
    }
    function csrfSafeMethod(method) {
        // these HTTP methods do not require CSRF protection
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }
    $.ajaxSetup({
        beforeSend: function(xhr, settings) {
            if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                xhr.setRequestHeader("X-CSRFToken", csrftoken);
            }
        }
    });发布于 2019-08-31 14:58:16
单击处理程序不会阻止事件的传播。当您的事件处理程序运行后,事件将传播,并最终将表单作为常规浏览器POST提交。你需要防止这种情况发生
$('#go').click(function(event) {
    event.stopPropagation();发布于 2019-08-31 22:02:47
我建议在每个用于测试的ajax.post中添加您的cookie,以确保cookies中生成的令牌是正确的。
示例:
$.ajax({
    type: 'POST',
    url: "",
    data: {
        username: $("#username").val(),
        email: $("#email").val(),
        password: $("#password").val(),
        'csrfmiddlewaretoken': getCookie('csrftoken')
    }
})在你的代码中。您在JS中定义了getCookie方法,创建了变量csrf_token,并在ajaxSetup中实现了该变量。令牌正在更改,但您的脚本不会重新加载它。
如果要使用ajax.setup,请在其中放入getCookie方法,以确保ajax在发送前重新获取正确的令牌。
https://stackoverflow.com/questions/57735836
复制相似问题