Django

Implement Pagination for Listing Records

๐Ÿ“Œ Introduction

When there are many records in a database table, showing everything on one page is not a good idea. The page becomes long and difficult to read.

Pagination solves this problem by:

  • showing only a few records on each page
  • providing page navigation like Previous, Next, First, and Last

In this program, we will display student records page by page.


๐ŸŽฏ Program Statement

๐Ÿ‘‰ Implement pagination for listing records.


๐Ÿง  Concept

This program uses:

  • Django Paginator
  • model records
  • current page number from URL
  • template navigation links

โš™๏ธ Step 1: Use Existing Model

๐Ÿ“ File: models.py

๐Ÿ”น Path:

myproject/myapp/models.py

๐Ÿ”น Code:

from django.db import models

class Student(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
course = models.CharField(max_length=100)
email = models.EmailField(unique=True)

def __str__(self):
return self.name

โš™๏ธ Step 2: Create View for Pagination

๐Ÿ“ File: views.py

๐Ÿ”น Path:

myproject/myapp/views.py

๐Ÿ”น Code:

from django.shortcuts import render
from django.core.paginator import Paginator
from .models import Student

def student_pagination(request):
student_list = Student.objects.all().order_by('id')

paginator = Paginator(student_list, 3) # 3 records per page
page_number = request.GET.get('page')
page_obj = paginator.get_page(page_number)

return render(request, 'student_pagination.html', {
'page_obj': page_obj
})

๐Ÿง  Explanation

  • Student.objects.all().order_by('id') fetches all student records in order
  • Paginator(student_list, 3) divides records into pages with 3 records each
  • request.GET.get('page') reads the page number from the URL
  • get_page() returns the requested page safely

โš™๏ธ Step 3: URL Mapping

๐Ÿ“ File: urls.py

๐Ÿ”น Path:

myproject/myproject/urls.py

๐Ÿ”น Code:

from django.contrib import admin
from django.urls import path
from myapp import views

urlpatterns = [
path('admin/', admin.site.urls),
path('student-pagination/', views.student_pagination, name='student_pagination'),
]

โš™๏ธ Step 4: Create Template

๐Ÿ“ File: student_pagination.html

๐Ÿ”น Path:

myproject/templates/student_pagination.html

๐Ÿ”น Code:

<!DOCTYPE html>
<html>
<head>
<title>Student Pagination</title>
</head>
<body>

<h1>Student Records with Pagination</h1>

{% if page_obj %}
<table border="1" cellpadding="10">
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
<th>Course</th>
<th>Email</th>
</tr>

{% for s in page_obj %}
<tr>
<td>{{ s.id }}</td>
<td>{{ s.name }}</td>
<td>{{ s.age }}</td>
<td>{{ s.course }}</td>
<td>{{ s.email }}</td>
</tr>
{% endfor %}
</table>

<br>

<div>
{% if page_obj.has_previous %}
<a href="?page=1">First</a>
<a href="?page={{ page_obj.previous_page_number }}">Previous</a>
{% endif %}

<span>
Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}
</span>

{% if page_obj.has_next %}
<a href="?page={{ page_obj.next_page_number }}">Next</a>
<a href="?page={{ page_obj.paginator.num_pages }}">Last</a>
{% endif %}
</div>

{% else %}
<p>No records found.</p>
{% endif %}

</body>
</html>

๐Ÿง  Explanation

  • page_obj contains only the records for the current page
  • {% for s in page_obj %} displays those records
  • has_previous and has_next are used to show navigation links
  • page_obj.number shows the current page
  • page_obj.paginator.num_pages shows the total number of pages

โš™๏ธ Step 5: Run Server

python manage.py runserver

๐ŸŒ Step 6: Output

Open:

๐Ÿ‘‰ http://127.0.0.1:8000/student-pagination/

If you have 10 records and page size is 3, then:

  • Page 1 โ†’ records 1 to 3
  • Page 2 โ†’ records 4 to 6
  • Page 3 โ†’ records 7 to 9
  • Page 4 โ†’ record 10

Example URL for second page:

http://127.0.0.1:8000/student-pagination/?page=2

๐Ÿง  How It Works

  1. View fetches all student records
  2. Paginator splits them into pages
  3. URL provides page number
  4. View sends selected page to template
  5. Template displays only those records
  6. Navigation links let user move across pages

๐Ÿ”ฅ Key Concepts

Import Paginator

from django.core.paginator import Paginator

Create Paginator

paginator = Paginator(student_list, 3)

Get Current Page Number

page_number = request.GET.get('page')

Get Page Object

page_obj = paginator.get_page(page_number)

Loop Through Page Records

{% for s in page_obj %}

โš ๏ธ Common Errors

โŒ Forgot to import Paginator

Django will show an import error.

โŒ Used students instead of page_obj in template

You must loop through:

{% for s in page_obj %}

โŒ Page links not working

Check that the URL contains:

?page=2

โŒ No ordering in queryset

Use:

Student.objects.all().order_by('id')

โŒ No records in database

Then pagination will not display meaningful results.


๐Ÿงช Practice Questions

  1. Change page size from 3 to 5
  2. Show clickable page numbers
  3. Add serial number column
  4. Add Bootstrap styling to pagination
  5. Combine pagination with search

๐ŸŽค Viva Questions & Answers

1. What is pagination in Django?

Pagination is the process of dividing many records into smaller pages for easy display and navigation.

2. Why do we use pagination?

Pagination improves readability and performance by preventing too many records from appearing on one page.

3. What is the Paginator class?

Paginator is a Django class used to divide a queryset or list into multiple pages.

4. What does Paginator(student_list, 3) mean?

It means only 3 records will be shown on each page.

5. What is page_obj?

page_obj is the object returned by paginator for the current page. It contains records and pagination information.

6. What is request.GET.get('page') used for?

It gets the current page number from the URL query string.

7. What is the use of has_previous?

It checks whether a previous page exists.

8. What is the use of has_next?

It checks whether a next page exists.

9. What does page_obj.number return?

It returns the current page number.

10. Why is pagination important in real applications?

Because real applications often contain large amounts of data, and pagination makes the interface cleaner and faster.


๐Ÿ”— Navigation

๐Ÿ‘‰ Next Post: Register a Model in Django Admin and Display Records
๐Ÿ‘‰ Back to List: Django Programs (60 Questions with Solutions)


Further Reading

Introduction to Django Framework and its Features

Django Practice Exercise

Examples of Array Functions in PHP

Basic Programs in PHP

Registration Form Using PDO in PHP

Inserting Information from Multiple CheckBox Selection in a Database Table in PHP

programmingempire

princites.com

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *