Django Python Pagination Tutorial Example

Published On: 05/07/2022 | Category: Django Python


Hi Dev,

In this tutorial, I will show you django pagination example. we will help you to give example of django python pagination bootstrap 4 example. In this article, we will implement a how to add pagination in python django. this example will help you how to create pagination in django. So, let's follow few step to create example of how to include pagination in django.

Here i explained simply step by step example of how to how to create pagination in django.

Step 1 : Create a Project

In this step, we’ll create a new django project using the django-admin. Head back to your command-line interface and run the following command:

django-admin startproject example
Step 2 : Create a App
python3 manage.py startapp pagination
Step 3 : Update setting.py

In this step we require to do two things in our settings.py file, One is to change the path of template look up directory. Second one is to configure our media folder. Add the below lines to your settings.py file:

Next, you need to add it in the settings.py file as follows:

import os

....
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'pagination',
]
Step 4 : Database Setup

Next step, we will modify the settings.py file and update the database settings to configure the mydb database:

settings.py
DATABASES = {  
    'default': {  
        'ENGINE': 'django.db.backends.mysql',  
        'NAME': 'example',  
        'USER':'root',  
        'PASSWORD':'root',  
        'HOST':'localhost',  
        'PORT':'3306'  
    }  
}  
Step 5 : Creating the Views

In this step, we need to create the views for performing fetch record to the database.Open the pagination/views.py file and add:

pagination/views.py
from django.shortcuts import render
from .models import Post
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

# Create your views here.

def index(request):
    posts = Post.objects.all()
    page = request.GET.get('page', 1)

    paginator = Paginator(posts, 3)
    try:
        posts = paginator.page(page)
    except PageNotAnInteger:
        posts = paginator.page(1)
    except EmptyPage:
        posts = paginator.page(paginator.num_pages)

    return render(request, 'index.html', { 'posts': posts })
Step 6 : Creating the Views

Next, open the pagination/templates/index.html file and the add:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Python Django Pagination Example</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.slim.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />
</head>
<body>
    <div class="container mt-5">
        <div class="row">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-header">
                        <div class="row">
                            <div class="col-md-9">
                                <h3>Python Django Pagination Example - <span class="text-primary">Tuts-Station.com</span></h3>
                            </div>
                        </div>
                    </div>
                    <div class="card-body">
                        <table class="table table-bordered table-hover">
                            <thead>
                                <tr>
                                    <th width="150">Title</th>
                                    <th width="200">Content</th>
                                </tr>
                            </thead>
                            <tbody>
                                {% for post in posts %}
                                    <tr>
                                        <td>{{ post.title }}</td>
                                        <td>{{ post.description }}</td>
                                    </tr>
                                    {% empty %}
                                        <tr class="text-center">
                                            <td colspan="4">There are no Record Found!</td>
                                        </tr>
                                {% endfor %}
                            </tbody>
                        </table>

                        <!--Pagination-->
                        <nav aria-label="Page navigation example">
                          <ul class="pagination justify-content-end">
                            {% if posts.has_previous %}
                              <li class="page-item">
                                <a class="page-link" href="?page={{ posts.previous_page_number }}">Previous</a>
                              </li>
                            {% else %}
                              <li class="page-item disabled">
                                <a class="page-link" href="#" tabindex="-1" aria-disabled="True">Previous</a>
                              </li>
                            {% endif %}
                            {% for i in posts.paginator.page_range %}
                              {% if posts.number == i %}
                                <li class="page-item active" aria-current="page">
                                  <span class="page-link">
                                    {{ i }}
                                    <span class="sr-only">(current)</span>
                                  </span>
                                </li>
                              {% else %}
                                <li class="page-item"><a class="page-link" href="?page={{ i }}">{{ i }}</a></li>
                              {% endif %}
                            {% endfor %}
                            {% if posts.has_next %}
                              <li class="page-item">
                                <a class="page-link" href="?page={{ posts.next_page_number }}">Next</a>
                              </li>
                            {% else %}
                              <li class="page-item disabled">
                                <a class="page-link" href="#" tabindex="-1" aria-disabled="True">Next</a>
                              </li>
                            {% endif %}
                          </ul>
                        </nav>
                        <!--end of Pagination-->

                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>
Step 7 : Creating Urls

In this section, we’ll create the urls to access our views.Go to the urls.py pagination/urls.py file and update it as follows:

pagination/urls.py
from django.contrib import admin
from django.urls import path

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', index, name = 'index'),
]
Run the Server

In this step, we’ll run the local development server for playing with our app without deploying it to the web.

python manage.py runserver

Next, go to the http://localhost:8000/ address with a web browser.

I Hope It will help you....