Dmitrii
Dmitrii

Reputation: 624

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?

Upvotes: 2

Views: 2394

Answers (2)

dev-jeff
dev-jeff

Reputation: 311

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)

Upvotes: 0

Dmitrii
Dmitrii

Reputation: 624

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

Upvotes: 3

Related Questions