Mike Johnson
Mike Johnson

Reputation: 37

Django Rest Framework ModelViewSet View Not seeing CSRFToken from datatables

I'm using the djangorestframework-datatables package in addition to djangorestframework. In addition to the ajax setup provided in the django docs that sets the X-CSRFToken in the header, I set CSRFToken in the header with the datatables ajax function:

Data.columns = [];
  $('th').each(function(item,i){
    Data.columns.push({'data': $(this).text().trim()})
  });

  $('#searchtable').DataTable({
    'serverSide': true,
    'ajax': {
      'url': '/api/v1/reports/?format=datatables',
      'type': 'POST',
      'columns': Data.columns,
      'headers': {'CSRFToken': Data.csrftoken },
    }
  });

Here is the drf code for the view I am writing about:

class ReportViewSet(viewsets.ModelViewSet):
    queryset = Report.objects.all()
    serializer_class = ReportSerializer
    permission_classes = [IsAuthenticated]

The error I'm getting is: "CSRF Failed: CSRF token missing or incorrect" - this is in the Response

Can anyone help?

Upvotes: 0

Views: 154

Answers (1)

Matthew Hegarty
Matthew Hegarty

Reputation: 4306

In the example app it is configured as follows:

$('#albums_post').DataTable({
        "serverSide": true,
        "ajax": {
            "url": "api/post-list/albums/?format=datatables",
            "type": "POST",
            "beforeSend": function(xhr) {
                xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token|escapejs }}");
            }
        },

Upvotes: 0

Related Questions