Search code examples
djangodjango-csrf

Ajax, CSRF and DELETE


I use the getCookie function from the django documentation to get the csrfmiddlewaretoken value.

I have the following ajax call:

var url = reverse_removeprofile.replace(/deadbeef/, key);
$.ajax({
    type:          "DELETE",
    url:           url,
    data:          "csrfmiddlewaretoken=" + getCookie("csrftoken"),
    success:       function() { ... },
});

When this code gets executed then django raises a 403 exception telling me that the CSRF verification failed. However, if I change the type from DELETE to POST then django is happy about it and doesn't complain at all.

I was not really able to find something useful in Google about this, but I've found this (now closed and fixed) ticket: https://code.djangoproject.com/ticket/15258

If I understand it correctly then this issue has been fixed in the 1.4 milestone. I use django 1.4 but still I cannot verify the CSRF token with a DELETE request.

Am I missing something here?


Solution

  • This appears to be a jQuery bug, caused by some confusion as to whether DELETE data should be attached to the URL (like a GET request) or the request body (like a POST)

    See this bug report.

    You can probably get around this by using the alternative CSRF method for AJAX calls, setting an X-CSRFToken header on the request. Try changing your AJAX call to look like this:

    $.ajax({
        type: "DELETE",
        url: url,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("X-CSRFToken", getCookie("csrftoken"));
        },
        success: function() { ... },
    });