Photo by Benjamin Davies on Unsplash

Django tricks: How to let users change page size with pagination

Adrien Van Thong


In a previous article, I went over how to leverage Django’s class-based-views to very quickly add pagination to an existing ListView class. In short, by adding a single line to our CBV, i.e.paginate_by = 123 the app developer has turned an un-paginated CBV into a paginated one.

But what if you wanted to let your users choose how big each page should be? In today’s very short article, I will show you how to very quickly grant your users this capability.

Turns out, CBVs in Django make this extremely simple as well. This time, instead of using the paginate_by field, we’ll instead overwrite the get_paginate_by method, and have it read in the value from GET parameters, as seen below:

from django.views.generic import ListView

class MyModelListView(ListView):
model = MyModel
template_name = 'my_template.html'
context_object_name = 'my_models'

def get_paginate_by(self, queryset):
return self.request.GET.get('page_size', 25)

In this example, we read in the GET parameter page_size with a default value of 25 (in case the parameter was not passed in). You could also use this trick to set the page size based on other factors, for example a user’s personal setting.

Next, we update our template with some links to provide the user some options for changing the page size. We’ll leverage the request.get_full_path context variable to ensure any other GET params present are preserved.

Results per page:
<li><a href="{{ request.get_full_path }}&per_page=10">10 results</a></li>
<li><a href="{{ request.get_full_path }}&per_page=25">25 results</a></li>
<li><a href="{{ request.get_full_path }}&per_page=50">50 results</a></li>
<li><a href="{{ request.get_full_path }}&per_page=100">100 results</a></li>

Alternatively, you can leverage Django forms to generate a dropdown or text field for this purpose, in this particular case I found that plopping down a few links to be the simplest and most straight-forward solution.

It’s that simple! Class-Based-Views once again provide an extremely elegant and simple way to add rich functionality to our pages, just by overwriting a single method. Happy coding!