Search code examples
djangodjango-viewsdjango-pagination

How to add extra context data in LISTVIEW without breaking built-in pagination


Question about pagination issue:

Why if I have for example following LISTVIEW:


class BoatListView(ListView):
    model = BoatModel
    template_name = "boats.html"
    paginate_by = 5

    def get_context_data(self, *, object_list=None, **kwargs):
        context = ListView.get_context_data(self, object_list=None, **kwargs)
        context["boats"] = BoatModel.objects.all()
        context["images"] = BoatImage.objects.all()
        return context

and I would use “boats” and “images” context in template , for example :


{% for boat in boats %}
some code here
{% endfor %}
...
…
….
{% bootstrap_pagination page_obj    %}

paginator will not work at all in this case ( bootstrap one or original Django https://docs.djangoproject.com/en/2.2/topics/pagination/#using-paginator-in-a-view), no difference?

But as soon as I change “boats” and “images” to “object_list” - paginator would begin pagination.

Whats the problem and how in this case could I add extra context in view if I need to do so within ability to use paiginator indeed?

Thank you!


Solution

  • ListView declares an attribute object_list which takes the queryset from get_queryset(). When constructing the context, this attribute is used to define pagination. You can override the behaviour of the pagination in get_context_data itself by changing what is sent as a queryset in self.paginate_queryset(queryset, page_size)(I don't see a reason to do this though).

    Take a look at how ListView works here.