Search code examples
jquerypythonajaxdjangocsrf

Sending a jQuery POST to a Django View


I am sending a POST request via $.ajax() to a Django view from a page that is on HTTP - I used the AJAX snippet for CSRF provided here. I can view the csrftoken cookie as Secure in Firebug; I suppose this is why the the X-Csrftoken header for the POST request is being sent as null.

Is there any way I can actually access this cookie's value? I am currently bypassing the 403 error (because of the POST being sent with a null CSRF token header) by adding @csrf_exempt to my view - but would like a proper CSRF method in place.

UPDATE FOR CLARITY: I am not submitting this data via forms. I am simply sending the POST when a javascript file (containing the AJAX call) is loaded on the page.


Solution

  • What I do for getting a proper csrf solution in place is this:

    include my {% csrf_token %} in a place it makes sense.

    var csrfToken = $('input[name="csrfmiddlewaretoken"]').val();
    $.ajax({
        url: $form.attr('action'),
        type: 'POST',
        data: postData,
        csrfmiddlewaretoken: csrfToken,
        dataType: 'json',
        success: function(data) { }
    });
    

    I have struggled to get this working:

    var csrftoken = $.cookie('csrftoken');
    $.ajaxSetup({
        beforeSend: function(xhr, settings) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    });
    

    But so far the first solution has proven to be the one that works best.