Isn’t it delightful when things just work? That’s how it is for Django pagination feature.
Say you are writing a blog in Django. Actually seems like a silly idea. If you want a blog, get yourself a static blog, or tumblr, or wordpress, or blogger (is it still popular?). Ok, maybe it’s not a blog. Probably you want to display a list of books in a paginated way. Definitely not cool to list all 2k books on a single page.
I like Django class-based views. They do for you all the hard work if you stick to the basics. So let’s start writing a CBV. Assume the model contains any kind of gibberish.
This is basically what we ought to do to enable pagination. Just specify how many objects we want on one page. Let’s take a look at the route and the template.
Now if you start your server and access the URL
127.0.0.1:8000/books/ you will
get 10 book objects listed on the first page. In order to access the second page
you need to enter
127.0.0.1:8000/books/?page=2. But your user isn’t supposed
to know that (don’t even think about writing a manual for that and giving it
to the end user). That’s why we will create pagination buttons.
ListView is so smart that it will add to your context some special
objects that will allow you to build those pagination buttons. In fact the
pagination we will build is reusable, so we will put in a separate snippet and
include to any template that requires pagination.
Now back to our
Dead simple. And this snippet will serve you well for all kinds of list views.