Django Pagination

Django is an open-source free to use python based web framework. Django provides many inbuilt tools for web developers to provide rapid web development. One of these tools is pagination. Pagination is the technique to divide the content of one large page into many smaller pages. Pagination can be found in many web browsers, blogs, websites, etc.

Django Pagination

Django provides some classes to support pagination. Paginator class provides the functioning of pagination in Django. We can pass QuerySet to the paginator class.

The paginator class resides in Django/core/paginator.py.  So if we want to use pagination in our project, we have to import it to our project.

From Django.core.paginator import Paginator

Paginator Class

The Paginator class takes the QuerySet as an input and then divides it into page objects displayed on different pages. The paginator class is connected to a view and then called inside a template.

Syntax:

class Paginator(object_list, per_page, orphans=0, allow_empty_first_page=True)

Arguments:

  • Object_list: This is a required argument. It is a list of objects which we want to display on the page. We can also provide QuerySet, a tuple, or other sliceable objects with len() or count() method.
  • Per_page: This is also a required argument. It represents the maximum number of objects we want to display on our page.
  • Orphans: This is an optional argument. It is used to skip the last page if there are very few objects in it. If the number of items on the last page is less than or equal to the orphan, then those items will get shifted to the previous page.
  • Allow_empty_first_page: This is also optional. It decides whether or not to keep the first page empty. If this is set to false and the object list is null, then an empty page error will be raised.

Methods:

  • Get_page(number):It returns the page object with the index equals number starting from 1. If the given value is a negative number, it will return the first page, and if the value is greater than the page number, then the last page will be returned.
  • Page(number): This returns a page object with an index range from 1. This will show an error if the value cannot be converted to an integer by calling int() or the page number does not exist.

Attributes:

  • Count:Returns the total number of objects on all the pages.
  • Num_pages:Returns the total number of pages.
  • Page_range:It returns an index-1 based range iterator of page numbers.

Example:

Now we will use pagination in our project. In this project, we are rendering a list of books and their authors, and now we want to use pagination to divide the books across different pages. We have defined the Books model in models.py. To use the pagination, use the below code in the views.py file.

View.py:

fromdjango.shortcuts import render
fromdjango.core.paginator import Paginator 
from .models import Book


def index(request):
books = Book.objects.all()
book_paginator = Paginator(books, 20)
page_num = request.GET.get('page')
page = book_paginator.get_page(page_num)
context = {
        'count' : book_paginator.count,
        'page' : page
    }
return render(request, 'books/index.html', context)

In this code, first, we have imported the Paginator class.  Then the book's objects are divided into a total 20 number of different pages. Then we are fetching the page number from GET. After getting the page number, we can get the content of that page by the get_page() method.

Index.html:

<!DOCTYPE html>
<html lang="en">
……..
……..
<body>
<h2>Total Number of Books: {{ count }}</h2>
<h2>Page Number: {{ page.number }}</h2>


    {% for book in page.object_list %}
<div class="book-item">{{ book.title }} by {{ book.author}}</div><br>
    {% endfor %}


<div class="page-links">
        {% if page.has_previous %}
<a href="{% url 'index' %}?page={{ page.previous_page_number }}">Previous Page</a>
        {% endif %}
        {% if page.has_next %}
<a href="{% url 'index' %}?page={{ page.next_page_number }}">Next Page</a>
        {% endif %}
</div>


</body>
</html>

On this page, we have displayed the information, previous and next page links. We have skipped the styling for this file.

Django Pagination

Class Page

The page object is generally not created manually. Rather, we use them by iterating through  Paginator or Paginator.page().

Syntax:

class Page(object_list, number, paginator)

Arguments:

  • Object_list:It represents the list of objects.
  • Number:Number represents the number of the page object.
  • Paginator:It is the paginator object for which we are constructing this page.

Methods:

  • has_next(): A Boolean argument returns True if there is a page next to this page.
  • has_previous():A Boolean argument returns True if there is a page previous to this page.
  • next_page_number():Returns the page number of the next page, raises an error if the next page does not exist.
  • previous_page_numer():Returns the page number of the previous page, raises an error if the previous page does not exist.
  • has_other_pages():A Boolean argument, returns True if previous or next page exists.

Related Topics

Django Stack

Django is a popular Python web application framework that adheres to the "batteries-included" tenet. Batteries-guiding included idea is that common functionality for creating web applications should be provided with the...

5 minutes read.

Uses of Django

Django is a free and open-source Python-based web framework, which offers great functionalities to its users. Django was developed in 2003, and the final version was released in 2008 by...

3 minutes read.

Django Create Superuser

For managing the website, we need an Admin while creating the Django application. In order to create the admin user, create superuser command is used. The superuser is called the...

3 minutes read.

Django Installation

Django Installation Django development environment consists of installing and setting up Python, Django, and a Database System since Django deals with a web application. Below the statement will guide you through installing Python 3.8.0 and...

2 minutes read.

Django Class Based Views

Class-based views were developed to solve the problem of customizing function-based generic views. We can arrange our view code Object-Oriented by using class views. Class-based views do more than function-based...

3 minutes read.

Django and React

This article will discuss the overview of Django and React, their advantages, applications, and most importantly, how to implement react in Django. What is Django? Django is a free and open-source web...

6 minutes read.

Django Filters

Django is a high-level python based web framework. Django is mostly used as a backend engine for websites. Nowadays, every website communicates to a database to fetch all the information...

3 minutes read.

Django Framework

Django is a popular high-level open-source web development Python framework based on follows Model View Template (MVT) architecture that allows rapid development. It. It provides common functionality like Admin Interface,...

3 minutes read.

Django Channels

Channels is a project that uses Django and adds some functionalities beyond the traditional HTTP by using WSGI and ASGI.  We can use both synchronous and asynchronous requests with ASGI...

5 minutes read.

Django Celery

Django is a python-based web framework. It is an open-source and free-to-use framework. Django uses the Model View Template architecture. Django provides many functionalities to web developers. One of these...

3 minutes read.

How to create an app in Django

Create an application in Django Django is famous for its unique and fully managed application structure. For each functionality, an application can be created as a completely independent module. This article will take...

2 minutes read.

How to Uninstall Django from cmd

Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

Django Authentication

Django is an open-source free to use web framework which is based on Python. Django uses Model-View-Template as its architecture. The final version of Django was released in 2008. Django...

4 minutes read.

Django Messages

Django Framework Django is a framework that can make web applications more accessible and faster. Django is an open-source collection of python libraries, and Django can be used for both the...

6 minutes read.

How to connect Django with Mysql

Any web application contains some data that comes from the input of the end-users. Thus, the database is required to handle those data. Several databases could be used to connect...

3 minutes read.

Creating View in Django

Creating View in Django    Django views are a key component of the frameworkbased applications.We are using Python function or class at their simplest, which takes up a web query and returns a web response.Views are used to get objects from the server, change objects if needed, render types, return HTML, and much more. Class Based View and Function based Django has two types of views: views based on functions (FBVs) and views based on class (CBVs).Initially, Django began with only FBVs, but then introduced CBVs as a way to model features so we didn't have to write boilerplate (i.e. the same software) code again and again.CBVs would be a way to increase efficiency, so you don't have to write as much code as you can. CBVs are classes of Python at their heart. Django ships with a range of "model" CBVs with pre-configured features that can be reused and often expanded.Then helpful names are given to these classes that explain what kind of functionality they provide.These are often referred to as "universal views" because they provide solutions to specific needs. The classes have a journal View function, or "view" for short, is simply a Python program that uses a web query and returns a web response. This response may include the HTML content of a web page, or a redirect, or a 404 error, or an XML file, or an image, etc. Example: You use a view to create a web page, remember that you need to connect a view to a URL to see it as a web page. Simple View We will create a simple view in myapplication to say “Welocome to django application” See the following view – from django.http import HttpResponse ...

4 minutes read.

Django Tutorial

Django Introduction It is a web application framework written in a python programming language. It based on the MVT( Model View Templet) design pattern. It takes a short time to build an application...

2 minutes read.

Django Create Project

Django is an open-source free to use web framework which is based on Python. Django uses Model-View-Template as its architecture. The final version of Django was released in 2008. Django...

4 minutes read.

Best Django courses

In this tutorial, we will see various courses in python Django available on the internet. Django has become popular these days, so courses on it are also increasing day by...

7 minutes read.

Django ORM

Django is a Python web framework that enables easy and quick web development. Django has a handy and powerful feature called Django Object Relational Mapper, also known as Django ORM,...

3 minutes read.