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?

Answers


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() { ... },
});

Need Your Help

Scale image keeping its aspect ratio in background drawable

android scaling android-drawable android-bitmap android-background

How do I make a background image fit the view but keep its aspect ratio when using <bitmap /> as a background drawable XML?

Set socket timeout in Ruby via SO_RCVTIMEO socket option

ruby sockets io timeout tcp-ip

I'm trying to make sockets timeout in Ruby via the SO_RCVTIMEO socket option however it seems to have no effect on any recent *nix operating system.