-->

Django and JEditable: CSRF error

2019-09-10 15:22发布

问题:

I started using the Jeditable plugin with Django and quickly ran into a CSRF error: "CSRF verification failed. Request aborted.", "CSRF token missing or incorrect"

As of this writing the Jeditable plugin seems have been last updated in 2008--sometime after this Django began requiring CSRF tokens for POST requests.

How do you add Django CSRF data to Jeditable?

回答1:

The answer to this question came from a similar jeditable post on CSRF. The CSRF token may be added in the "submitdata" variable.

Expanding the 1st jeditable example for a Django post look something like this:

$(document).ready(function() {
   $('.edit').editable('http://www.example.com/save.php', { 
        submitdata : { csrfmiddlewaretoken : "{{ csrf_token }}"}
    });
});

Note, in order to show the "csrf_token" value instead of an entire form field, the "csrf_token" is wrapped in {{..}} instead of {% .. %}.



回答2:

The preferred method for providing the CSRF token through AJAX requests is by setting the X-CSRFToken header to the value of the CSRF token. You'll need to modify the constructed request object to set the header value.

There's also a helper function provided to get the CSRF token from the cookie, rather than relying on providing it in the template, which considerably simpifies things, i.e. you don't have to ship the JS code inline or set the token as a variable in JS in the template itself.