Users Online

· Guests Online: 47

· Members Online: 0

· Total Members: 188
· Newest Member: meenachowdary055

Forum Threads

Newest Threads
No Threads created
Hottest Threads
No Threads created

Latest Articles

Articles Hierarchy

Django Tutorial

Django Pagination

Django Pagination

Introduction to Django Pagination

The pagination is used for setting the pages and display them. It helps to set the number of pages. django.core.paginator is used for declaring a paginator. The pagination helps to set the page details and the total number of pages used. So the process of pagination can be used. The pagination allows to declare the pages associated and the pages associated to it. Django’s capability to produce inbuilt pagination packages is a key advantage of designing the pages in Django setup. Pagination is among the effective ways to declare the items. The import code change section for pagination process is on the All-users section.

Syntax:

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

How does 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:

1. (Forms.py)

The forms files will have all the fields to be declared. These fields associated to the forms.py file will have all the fields which needs 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

2. (models.py)

The Models files will have all the fields to be declared. These fields associated to the models.py file will have all the fields which needs to be a part of the table declaration. The 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

3. Views.py

The import code change section for 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})

4. HTML

The below are the HTML changes for pagination, the process involves declaring a table structure with username and email from the reference table. Next, the section of code for setting the pages as a movable object is listed. Here the second section allows flexible 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>

Output:

Django Pagination-1

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 a key advantages of Django process.

Comments

No Comments have been Posted.

Post Comment

Please Login to Post a Comment.

Ratings

Rating is available to Members only.

Please login or register to vote.

No Ratings have been Posted.
Render time: 0.78 seconds
10,841,160 unique visits