django-rest-framework-datatables icon indicating copy to clipboard operation
django-rest-framework-datatables copied to clipboard

Default global and column search is not working in POST method

Open NAYcoder opened this issue 2 years ago • 1 comments

When I am using POST method, the default global search and column search is not working. The same worked when I used GET method and ViewSet. Then I changed the method to POST using ListAPIView. Then its not filtering based on the search parameters. Its giving complete list without filtering.

NAYcoder avatar Aug 08 '23 12:08 NAYcoder

@NAYcoder I had a similar issue, I had to change a datatables from GET to POST because I was hitting URL Length limits on my server. I had to do two things:

  1. On client side I had to inject the csrf token on the POST call:
<html>
...
<! -- django renders this as an input -->
{% csrf_token %}
...
</html
<script>
  // get the token value
  const token = $('input[name="csrfmiddlewaretoken"]').val();
  const extraData = (data) => {
    // Add the CSRF token to the data form so it's not blocked by Django
    data.csrfmiddlewaretoken = token;
    return data;
  };
  const table = new DataTable({
    ajax: {
        url: 'my/api/url?format=datatables',
        method: 'POST',
        data: extraData,
    },
    /// .. other things
  });
</script>
  1. On the server side, I was using ReadOnlyViewSet, I had to re-wire it to use ModelViewSet plus ListModelMixin:
class MyListAPI(ListModelMixin, GenericViewSet):

    queryset = models.MyModel.objects.all()
    serializer_class = serializers.MyModelSerializer

    def create(self, request, *args, **kwargs):
        """Rewire the create method to allow listing using POST method. """
        return super().list(request, *args, **kwargs)

juli4nb4dillo avatar Aug 30 '24 11:08 juli4nb4dillo