Home:ALL Converter>Django pagination with ListView and django-filter not working properly

Django pagination with ListView and django-filter not working properly

Ask Time:2018-07-07T20:35:21         Author:pjdavis

Json Formatter

I am using django-filter in a ListView which is causing problems with pagination. In my listview, when the page is loaded the pagination appears correct and shows page links for pages 1-7 at the bottom. However when I go to any of these pages it displays all model instances. For example, I click on page 2, the url is appended with ?page=2 and as I set paginate-by as 20 I expect objects with ids 21-40.

I know the problem is caused by the django-filter, since when I remove this from 'get_context_data' the pagination works correctly. I am only using 'self.queryset' as an argument in the django-filter object so I cannot work out why this is happening. The html for the pagination is contained in a base template which I extend in the templates for the ListView subclasses.

Any suggestions on why the pagination is not working correctly when I include the django-filter in the context data and/or what I should try in order to fix it would be greatly appreciated.

Base ListView and a subclass:

class BaseCompoundListView(ListView):
    queryset = Compound.objects.all()
    template_name = 'compounds/compound_list.html'
    paginate_by = 20        

    def get_context_data(self, **kwargs):
        context = super(BaseCompoundListView, self).get_context_data(**kwargs)
        context['odor_types'] = OdorType.objects.values('term')
        compound_filter = CompoundFilter(self.request.GET, queryset=self.queryset)
        context['compound_filter'] = compound_filter
        return context

class CompoundListView(BaseCompoundListView):

    def get_context_data(self, **kwargs):
        context = super(CompoundListView, self).get_context_data(**kwargs)
        context['page_header'] = 'All compounds'
        return context

The base template:

  {% block content %}{% endblock %}
  {% block pagination %}
  {% if is_paginated %}
    <div class="pagination">
    <span class="page-links">
    {% if page_obj.has_previous %}
       <a href="{{ request.path }}?page={{ page_obj.previous_page_number }}">previous</a>
    % endif %}
    <span class="page-current">
     Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.
     </span>
     {% if page_obj.has_next %}
     <a href="{{ request.path }}?page={{ page_obj.next_page_number }}">next</a>
     {% endif %}
     </span>
     </div>
     {% endif %}
    {% endblock %}

Author:pjdavis,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/51223297/django-pagination-with-listview-and-django-filter-not-working-properly
yy