Django and JEditable: CSRF error

对着背影说爱祢 提交于 2019-12-11 18:26:08

问题


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.



来源:https://stackoverflow.com/questions/13019488/django-and-jeditable-csrf-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!