Django Pagination

Django Pagination
Written by Sagar RabidasJanuary 3, 2022
14 min read
Django
0 VIEWS 0 LIKES 0 DISLIKES SHARE
0 LIKES 0 DISLIKES 0 VIEWS SHARE
Sagar Rabidas

Software Developer

Today in this blog, we will discuss Django Pagination

Django:-

Django is an open-source and free Python-based web framework. Released in 2005, it’s developed and maintained by the Django Software Foundation. Django has a 3-clause BSD license, and the latest version released is Django 3.2.

This high-level web framework makes it effortless to develop better web applications quickly with less code. Django encourages clean and pragmatic design for rapid web app development. Due to its readable syntax, it can save the time and effort of developers. It’s lightweight and flexible for use in both development and testing.

Django works on the Model-View-Template (MVT) architecture to make web app designing aesthetically pleasing and highly functional. It’s highly adaptable to different types of projects in multiple industries and involves several pre-made feature packages.

It’s excellent for creating complex applications. As it’s a Python-based framework, it helps develop products for data science, computation, artificial intelligence (AI) and machine learning (ML), and other scientific uses.

blogpost

Django Pagination:-

The pagination is used for setting the pages and showing them. It enables to set the number of pages. Django.Core.Paginator is used for declaring a paginator. The pagination helps to set the page info and the total number of pages used. So the manner of pagination may be used. The pagination lets in affirming the pages related and the pages associated with it. Django’s functionality to provide built-in pagination programs is a key benefit of designing the pages in Django setup. Pagination is a few of the effective methods to declare the gadgets. The import code change section for the pagination system is at the all-users segment.

Syntax:

Table_object = Table_name.objects.all()
Paginator_object = Paginator(Table_object, page_number)
Page_object = paginator.page(paginator_object)

Pagination work

  • Retrieve the objects to be displayed into a variable. So all the objects will get retrieved into the assigned variable.
  • Declare a paginator object and set the number of pages and the objects to be displayed in the object declaration.
  • Assign the page details to a render variable and pass the render variable to the HTML template. This will have the page displayed in the web address. The retrieval of the object and set up the variable.

Examples of Django Pagination

Following are the examples of Django pagination are:

  • (Forms.py)

The forms files will have all the fields to be declared. These fields associated with the forms.py file will have all the fields which need to be a part of the table declaration. A column-like these will be responsible for display.

from django import forms
from. models import Bride
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
# Create your forms here.
Rasi_CHOICES =(
("1", "Mesham"),
("2", "Rishabam"),
("3", "Mithunam"),
("4", "Kadakam"),
("5", "Simmam"),
("6", "Kanni"),
("7", "Thulam"),
("8", "Viruchikam"),
("9", "Thanusu"),
("10", "Makaram"),
("10", "Kumbam"),
("10", "Meenam"),
)
State_Choices = (
("1", "Mesham"),
("1", "Mesham"))
class Valueform(forms.ModelForm):
Rasi = forms.ChoiceField(choices = Rasi_CHOICES)
class Meta:
model = Bride
fields = "__all__"
class NewUserForm(UserCreationForm):
email = forms.EmailField(required=True,error_messages={'required': 'Please enter your name'})
def clean(self):
cleaned_data = super(NewUserForm, self).clean()
email_passed = cleaned_data.get("email")
if not "gmail.com" in email_passed:
print("came here")
raise forms.ValidationError("Sorry, the email submitted is invalid. All emails have to be registered on this domain only.")
return email_passed
class Meta:
model = User
fields = ("username", "email", "password1", "password2")
def save(self, commit=True):
user = super(NewUserForm, self).save(commit=False)
user.email = self.cleaned_data['email'] if commit:
user.save()
return user
  • (models.py)

The Models files will have all the fields to be declared. These fields associated with the models.py file will have all the fields which need to be a part of the table declaration. A column-like these will be responsible for display.

from django.db import models
from django.contrib.auth.models import User
# Model variables
# Create your models here.
class Bride(models.Model):
Django_Paginators_Example_name = models.CharField(max_length=200,null=True)
Django_Paginators_Example_thegai = models.CharField(max_length=200,null=True)
Django_Paginators_Example_State =  models.CharField(max_length=50,null=True)
Django_Paginators_Example_District = models.CharField(max_length=50,null=True)
Django_Paginators_Example_Address = models.TextField(null=True)
Django_Paginators_Example_Phone = models.BigInteger_Example_Field(null=True)
Django_Paginators_Example_profession = models.CharField(max_length=200,null=True)
Django_Paginators_Example_salary = models.BigInteger_Example_Field(null=True)
Django_Paginators_Example_Under_Graduation_Degree = models.CharField(max_length=200,null=True)
Django_Paginators_Example_Under_Graduation_college = models.CharField(max_length=400,null=True)
Django_Paginators_Example_Post_Graduation_Degree = models.CharField(max_length=200,null=True)
Django_Paginators_Example_Post_Graduation_college = models.CharField(max_length=400,null=True)
Django_Paginators_Example_Rasi = models.CharField(max_length=200,null=True)
Django_Paginators_Example_Nakshatra = models.CharField(max_length=200,null=True)
def __str__(self):
return self.name
  • Views.py

The import code change section for the pagination process is on the All-users section. Here the contents of the table for which the objects or elements are expected to be displayed are retrieved into an object. So, all the object entries will be retrieved. Then the paginator object is created. The paginator object defines the page being used. so, a page object will be created. The page object will be associated with the table objects and the number of pages to be associated. So, the total number of pages and the table details will be declared in the paginator class. This is a very important section of the pagination process.

def All_users(request):
User_entries =  User.objects.all()
page = request.GET.get('page', 1)
paginator = Paginator(User_entries, 5)
users = paginator.page(page)
print(" Has other pages : ",users.has_other_pages())
print(" Has next page : ",users.has_next())
print(" Has previous page : ",users.has_previous())
print(" Has previous page : ",users.has_previous())
print(" Start Index : ",users.start_index())
print(" End Index : ",users.end_index())
if users.has_next():
print(" Next page Number: ",users.next_page_number())
elif users.has_previous():
print(" Has Previous page Number: ",users.previous_page_number())
print(paginator,users)
return render(request,"All_users.html",{'users':users})
  • Views.py

The import code exchange segment for the pagination procedure is on the all-customers phase. Here the contents of the table for which the objects or factors are predicted to be displayed are retrieved into an object. So, all the item entries will be retrieved. Then the paginator object is created. The paginator item defines the web page getting used. So, a page object might be created. The web page object can be associated with the table objects and the number of pages to be associated. So, the entire wide variety of pages and the desk info might be declared within the paginator elegance. That is a completely crucial segment of the pagination manner.

def All_users(request):
User_entries =  User.objects.all()
page = request.GET.get('page', 1)
paginator = Paginator(User_entries, 5)
users = paginator.page(page)
print(" Has other pages : ",users.has_other_pages())
print(" Has next page : ",users.has_next())
print(" Has previous page : ",users.has_previous())
print(" Has previous page : ",users.has_previous())
print(" Start Index : ",users.start_index())
print(" End Index : ",users.end_index())
if users.has_next():
print(" Next page Number: ",users.next_page_number())
elif users.has_previous():
print(" Has Previous page Number: ",users.previous_page_number())
print(paginator,users)
return render(request,"All_users.html",{'users':users})
  • HTML

The below are the HTML modifications for pagination, the manner includes declaring a desk shape with username and e-mail from the reference table. Subsequently, the phase of code for placing the pages as a movable item is indexed. Right here the second phase lets in bendy movement between the pages. The first section mentions the content of the pages.

<html style="font-size: 16px;">
<head>
<title>Home</title>
{% load static %}
<link rel="stylesheet" href="{% static 'admin/css/Formpage.css' %}" media="screen">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1" . . .  />
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<!-- - -  Script -- - - >
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body class="body">
<nav class='navbar'>
<div class='navbar_div'>
<a class="navbar" onclick="redirect2()" >Home! </a>
<a class="navbar" onclick="redirect2()" >Contact</a>
</div>
</nav>
<table class="table table-bordered">
<thead>
<tr>
<th>Username</th>
<th>Email</th>
</tr>
</thead>
<tbody>
{% for user in users %}
<tr>
<td>{{ user.username }}</td>
<td>{{ user.email }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<body>
<script>
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e)
{
var image = document.getElementById('image');
image.src = URL.createObjectURL(input.files[0]);
}
reader.readAsDataURL(input.files[0]);
var download = document.getElementById('download');
download.src = URL.createObjectURL(input.files[0]);
download.setAttribute("download", 'sample.img');
download.click();
}
}
<script>
{% if users.has_other_pages %}
<ul class="pagination">
{% if users.has_previous %}
<li><a href="?page={{ users.previous_page_number }}">&laquo;</a></li>
{% else %}
<li class="disabled"><span>&laquo;</span></li>
{% endif %}
{% for i in users.paginator.page_range %}
{% if users.number == i %}
<li class="active"><span>{{ i }} <span class="sr-only">(current)</span></span></li>
{% else %}
<li><a href="?page={{ i }}">{{ i }}</a></li>
{% endif %}
{% endfor %}
{% if users.has_next %}
<li><a href="?page={{ users.next_page_number }}">&raquo;</a></li>
{% else %}
<li class="disabled"><span>&raquo;</span></li>
{% endif %}
</ul>
{% endif %}
<script>
function form1() {
window.location.href = "http://127.0.0.1:8000/form";
}
function redirect1() {
window.location.href = "http://127.0.0.1:8000/Mainpage";
}
function redirect2() {
window.location.href = "http://127.0.0.1:8000/";
}
</script>
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</body>
</html>

Conclusion

So, pagination is a process well allocated in Django. The pagination process of Django helps in the smooth declaration of pages in the Django setup. This helps to set and access pages in a very flexible manner. This is among the key advantages of the Django process.

Django
Django Pagination
Pagination
0 VIEWS 0 LIKES 0 DISLIKES SHARE
0 LIKES 0 DISLIKES 0 VIEWS SHARE
Was this blog helpful?
You must be Logged in to comment
Code Block
Sagar Rabidas
Software Developer
162 Blog Posts
15 Discussion Threads
Trending Categories
15
Software39
DevOps45
Frontend Development24
Backend Development20
Server Administration17
Linux Administration24
Data Center24
Sentry24
Terraform21
Ansible29
Docker28
Penetration Testing14
Kubernetes16
NGINX19
JenkinsX17
Techiio

Techiio is on the journey to build an ocean of technical knowledge, scouring the emerging stars in process and proffering them to the corporate world.

Follow us on:

facebooklinkdeintwitter

Subscribe to get latest updates

You can unsubscribe anytime from getting updates from us
Copyright techiio.com @2020 Kolkata, India
made with by Abhishek & Priyanka Jalan
Copyright techiio.com @2020
made with by Abhishek & Priyanka Jalan