[Answered ]-403 Forbidden and request.method showing GET in django

1👍

You can try this

<script type="text/javascript">

    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');
    $(document).ready(function () {
        $.ajax({
            type: 'post',
            url: "{% url "url_to_view" %}",
            headers: {"X-CSRFToken": csrftoken},
            data: {id: "something to view"},
            success: function (response) {
                alert("success");
                });
            },
            failure: function (response) {
                alert(response.d);
            }
        });
    });
</script>

1👍

You need to do something like this in JavaScript to correctly set the csrf token. It doesn’t need to part of the data, but rather the request headers

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-CSRF-Token", CSRF_TOKEN);
        }
    }
});

In django you don’t need to do a csrf_exempt as the above code will inject the CSRF token into every ajax request, if needed. (there is a very good reason why CSRF is there so it’s best not to exempt it)

Leave a comment