Search code examples
djangodjango-filterdjango-pagination

How to add pagination to FilterView


I've filtering view of django_filters.FilterSet which is called right from urls.py

url(r'^$', FilterView.as_view(filterset_class=ProductFilter, template_name='products/products.html'), name='products'),

and it's has no pagination, but when i add paginate_by = 20 in

url(r'^$', FilterView.as_view(filterset_class=ProductFilter, template_name='products/products.html'), paginate_by = 20, name='products'),

it adds my custom pagination page, but it's not handling data restricted by filters. So i can apply a few filters and it reduces data to, say 40 rows, but clicking on a second page it loads my all data without any filter. Could I specify that I want to paginate data after filtering somehow?


Solution

  • At the end I decided to create separate view and add queryset directly to context object like:

    class ProductView(ListView):
        model = Product
        template_name = 'products/products.html'
        paginate_by = 5
    
        def get_context_data(self, **kwargs):
            context = super().get_context_data()
            context['product_list'] = ProductFilter(self.request.GET, queryset=Product.objects.order_by('id')).qs
            return context