Django and JEditable: CSRF error

2019-09-10 15:06发布

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?

2条回答
Evening l夕情丶
2楼-- · 2019-09-10 15:54

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 {% .. %}.

查看更多
\"骚年 ilove
3楼-- · 2019-09-10 16:02

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.

查看更多
登录 后发表回答