[Fixed]-How to write a Django view for a POST request

14👍

This is by design. Your POST data must contain csrfmiddlewaretoken value. You can get it from your cookies and then send it with POST requests. Details here. For your specific case, you can do this –

<script>
$(function () {
    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');

    $("button")
        .button()
        .click(function (event) {
            var postdata = {
                'value1': 7,
                'value2': 5,
                'csrfmiddlewaretoken': csrftoken
            };
            $.post('', postdata); // POST request to the same view I am now
            window.alert("Hello world!"); // To know it is working
        });
});
</script>

4👍

You are receiving a 403 because of CSRF protection – you have not provided a token to protect yourself from attacks. The documentation tells you all you need to know.

Leave a comment