Datatables-Django CSRF Token Issues

Datatables-Django CSRF Token Issues

keila_ortizkeila_ortiz Posts: 10Questions: 3Answers: 0

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.

Answers

  • keila_ortizkeila_ortiz Posts: 10Questions: 3Answers: 0
    edited April 2019

    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'......
    
This discussion has been closed.