izimobil / django-rest-framework-datatables

Seamless integration between Django REST framework and Datatables.
http://django-rest-framework-datatables.readthedocs.io/en/latest/
MIT License
393 stars 89 forks source link

Default global and column search is not working in POST method #143

Open NAYcoder opened 1 year ago

NAYcoder commented 1 year ago

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.

juli4nb4dillo commented 2 weeks ago

@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)