2

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?

cezar
  • 11,616
  • 6
  • 48
  • 84
Dmitrii
  • 604
  • 2
  • 9
  • 30

2 Answers2

3

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
andilabs
  • 22,159
  • 14
  • 114
  • 151
Dmitrii
  • 604
  • 2
  • 9
  • 30
  • How did you manage to keep the filter form in your view? I'm trying to follow your solution. I can get the pagination but I lost the filter form. – Redjam Mar 16 '19 at 13:25
  • `{% for page_num in paginator.page_range %}` this is how i can get a paginator object in template and `product_list` as object containing filter. – Dmitrii Mar 18 '19 at 14:58
  • 2
    This is so in-conclusive answer. – Donald Apr 16 '20 at 20:51
  • also pass the form through context `context['form'] = context['product_list'].form` – Natnael A. Jun 25 '21 at 12:52
0

I found this to be much simpler to achieve pagination with filters on a given view:

class ProductView(ListView):
    model = Product
    template_name = 'products/products.html'
    paginate_by = 5
    context_object_name = 'products'

    def get_queryset(self):
        return Product.objects.filter(my_field=my_criteria)
dev-jeff
  • 173
  • 9