添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

I'm developing a Django application and using Datatables Editor. It's giving me a CSRF token error. In a normal HTML form I would just write {% csrf token%) as part of the form. But, I don't know how to do this with AJAX. I saw this example here:
https://docs.djangoproject.com/en/1.9/ref/csrf/

Django recommends using the js-cookies.js script, which I added.
"The above code could be simplified by using the JavaScript Cookie library to replace getCookie:

var csrftoken = Cookies.get('csrftoken');"

However, I don' know where to place it. I've been trying to copy/paste in different spots and can't figure it out. I also don't know if I need anythong else.

I figured it out. If someone ever needs this:
I added the js-cookies.js script as advised in the Django documentation:
https://docs.djangoproject.com/en/2.2/ref/csrf/ , which takes you to the github page:
Scroll down until you see: "Download the script here and include it (unless you are packaging scripts somehow else):"

In your script use the following:

script>

var csrftoken = Cookies.get('csrftoken');
var editor;
$(document).ready(function(){
      editor = new $.fn.dataTable.Editor({        
      ajax: {
        url: 'your_POST_url',
        type: 'POST',
        headers: {'X-CSRFToken': '{{ csrf_token }}'},
      table: "#results_table",
      idSrc: 'id'......
				DataTables designed and created by SpryMedia Ltd.
© 2007-2023 MIT licensed. Privacy policy. Supporters.