[Answered ]-Dajngo: Pagination in search results with Class-based views

1👍

This has not much to do with the view, but the links of the pagination. You can create a helper function in the view:

class SearchedResults(ListView):
    model = Quote
    paginate_by = 10
    template_name = 'quotes/index.html'
    context_object_name = 'quotes'

    def urlencode_search(self):
        qd = self.request.GET.copy()
        qd.pop(self.page_kwarg, None)
        return qd.urlencode()

    def get_queryset(self):
        query = self.request.GET.get('search_query')
        queryset = super().get_queryset(*args, **kwargs)
        if query:
            queryset = queryset.filter(
                Q(quote__icontains=query)
                | Q(tags__name__icontains=query)
                | Q(author__fullname__icontains=query)
            ).distinct()
        return queryset

In the template, you then link to a different page with:

<a href="?page={{ page_obj.next_page_number }}&amp;{{ view.urlencode_search }}">next page</a>

and this for all links that go to a page.

Leave a comment