Paginate properly, please!

Loud Noise Inc
2 min readJan 23, 2018

--

Working on a Django project, I found the excellent tutorial at https://simpleisbetterthancomplex.com/tutorial/2016/08/03/how-to-paginate-with-django.html for implementing pagination. All was well and good.. until I ran into two issues, one of which is also discussed in the comments for the above tutorial:

  1. If number of pages becomes too many, the whole paginated view becomes unwieldy:

2. The implementation does not handle query pagination properly. For example, if I search for 23rd page of all objects that contain the title = “Django”, the redirect should be to “someview.html?title=Django&page=23”, not “someview.html?page=23”.

I tried to use the code described in https://www.tummy.com/articles/django-pagination/ and just could not make it work, and it anyway was not doing what I was trying to do: I didn’t need ellipses in the page, just the neighboring pages.

So I created two custom tags. The first is in “proper_paginate.py”, which calculates the start and end indices. The code is quite straightforward, I hope. The second is in “link_name.py*” which generates the proper URL based on which page number we wish to go to. It is a bit of a pain to have to define two different tags but that’s how custom tag loading seems to work.

*: Thanks to Jabrail Lezgintsev’s comment, I got rid of link_name.py and replaced it with replace_url.py (the name isn’t important but the tag is much simpler and cleaner, just the way Python code is supposed to be).

Then, I just had to change my common paginator template (originally inspired by Vitor’s article).

And voila! The bar now works as expected:

Check the sources below and leave a comment on how to improve it.

Cheers!

--

--