In this example, I'm going to use a very simple implementation of a list view in django, where i'm going to simply render a view with 10 items in the database, so I'm going to paginate by 1, so I can see a single item rendered in the view on every page. All you need to do to paginate your model in a ListView is to declare and assign a value to paginate_by
:
Then in your template, you can simply iterate over every item in the context_object_name
, only the items of the page will be rendered:
Now, to render the pagination widget, you can use the following code that will render a Bootstrap 5 pagination widget. It will render 4 interaction buttons when there are multiple pages to navigate (First page, Previous page, Next Page and Last Page), as well as up to 7 buttons containing the number of the pages of the paginator:
At the end, your template file will look something like this:
In my template (a customized template based on Bootstrap 5), once this page is rendered the paginator looks like this:
Of course this is the default pagination widget of Bootstrap, however this is a nice start point if you're looking for extra customization of the widget in your Django project.
Including all GET parameters of the request in the pages buttons
In the previous implementation, we didn't handle what happens with the other GET parameters of the URL, we forced a single parameter namely page
. In case that you need to include as well the other GET parameters from the request on every link of every page, you need to include the following piece of template when the URL is generated for every button:
For example, in our implementation you can replace the page range block with the following one to include all the GET parameters (don't forget to do the same with the Next and Last button):
Happy coding ❤️!
0 Comments