Django Pagination

Manish Sangwan   28 January,2020  

Introduction

You may have come across a problem of displaying many objects in a single page. Pagination allows you to divide the objects into discrete pages. It is very difficult to show up all the objects in a single page. For example, if you are running a blog website, when you want to list all the post, it is better to divide the posts into pages.

Django provides a few classes that can help you to manage your paginated data i.e., data that are split across several pages, with “Previous/Next” links or list it into discrete page numbers. You can use the Django Pagination by including the class that lives in django/core/paginator.py

Jump into the code

Let’s understand by an example of Blog app.

Models.py: -

Now I have created 6 blogs of random title and content just to demonstrate the example.

After this, let’s create the blog list view in view.py.

Views.py: -

Now that we have completely setup our views, its time create the template view_all_blog.html.

Note: I have included all the necessary CSS and JS of jQuery and Bootstrap in home_base.html, and using the Template inheritance of Django, I have content block described in list.html

There are two types of pagination you can use in your template.

1.) Using only the previous and next buttons

Pagination can be done by providing two buttons for navigating either previous page or next page from the current page. This is the basic way to Paginate your Django Page. You could also show the page numbers along with the previous and next buttons.

 

Output: -

 

2.) Using Discrete Page Numbers

Listing the range of page numbers with left and right navigation of page can be another alternative to Paginate your page.

 

Output: -

0
Like