Forbidden (CSRF token missing or incorrect) Django error

夙愿已清 提交于 2019-12-03 17:27:40

The AJAX request must include the csrf, because it's another HTTP request, so please copy this code:

// 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 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);
        }
    }
});

After you setup that before sending AJAX request to set the csrf.

source

Or you can do it in a short way (without the codes written above), but sending all the data in the inputs field:

$.post(
    '/rango/tagger',
    $("#id_of_your_form").serialize(),
    function(data) {
        console.log(data);
    }
)
Abhyudai

Django requires a csrf token for accepting post requests. You can also add a property csrfmiddlewaretoken = {% csrf_token %} to your data if your script is inside the template.

For folks, using this inside an include js file, you can do something like:

<script>window.CSRF_TOKEN={{ csrf_token }}</script>`

and in your included js file use

$.post(url, { 'data': data + 'csrfmiddlewaretoken': window.CSRF_TOKEN },function(response){
    console.log(response)
  }
})
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!