Skip to content
Advertisement

How to filter and paginate in ListView Django

I have a problem when I want to paginate the filter that I create with django_filter, in my template it shows me the query set and filter but paginate does not work, I would like to know why this happens and if you could help me.

I’ll insert snippets of my code so you can see.

This is my views.py

PD: i have all the necesary imports.

@method_decorator(staff_member_required, name='dispatch')
class EmployeeListView(ListView):
    model = Employee
    paginate_by = 4

    def dispatch(self, request, *args, **kwargs):
        if not request.user.has_perm('employee.view_employee'):
            return redirect(reverse_lazy('home'))
        return super(EmployeeListView, self).dispatch(request, *args, **kwargs)
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['filter'] = EmployeeFilter(self.request.GET, queryset = self.get_queryset())
        return context

filters.py

import django_filters
from .models import Employee, Accident

class EmployeeFilter(django_filters.FilterSet):

    class Meta:
        model = Employee
        fields = {
            'rutEmployee' : ['startswith']
        }

Advertisement

Answer

You should override get_queryset.This means you have to put your filter in get_queryset like this:

@method_decorator(staff_member_required, name='dispatch')
class EmployeeListView(ListView):
    model = Employee
    paginate_by = 4

    def dispatch(self, request, *args, **kwargs):
        if not request.user.has_perm('employee.view_employee'):
            return redirect(reverse_lazy('home'))
        return super(EmployeeListView, self).dispatch(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['filter'] = EmployeeFilter(self.request.GET, queryset = self.get_queryset())
        return context
    
    def get_queryset(self):
        queryset = super().get_queryset()
        return EmployeeFilter(self.request.GET, queryset=queryset).qs

and use object_list instead of filter in employee_list.html like this:

{% for employee in object_list|dictsort:"id" reversed %}
Advertisement