Social Icons

Monday, January 17, 2022

Django Pagination System

1 - Brief reminder of the previous tutorial: student management with django

To achieve this paging system we will adopt the previous tutorial of student management:

1.1 - Creating a new new app django studentsApp

We start by creating a new django project and a django app called studentsApp

We then create a media directory in our mysite project which will be used to store the downloaded media. This folder needs to be configured in the file:

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
Next, let's configure the files of the studentsApp application: So that the media files or images... are accessible, we must add to the
file the following code:
+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) 
Thus our
file becomes:
from django.contrib import admin
from django.urls import path
from uploadFile import  views
from django.conf.urls.static import static
from . import settings

urlpatterns = [
    path('student/', views.student),
]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Now we need to register our application at the

1.2 - Creating a model for studentsApp

Consider the Students model example that we have already covered in the previous tutorial django models, to which we add a file field that allows students to attach their photos during registration:
# studentsApp/
from django.db import models
class Students(models.Model):
    name        = models.CharField(max_length=25)
    email       = models.EmailField(max_length=40)
    phone    = models.IntegerField(max_length=40)
    section      = models.CharField(max_length=25)
    photo           = models.FileField(upload_to = 'photos')
upload_to = 'photos'
argument that we added tells django that the uploaded files should be saved in a folder named

. Do you have to manually create this directory? Well don't worry! Django will create it automatically when running the script. 

The necessary migrations are then carried out:

python makemigrations studentsApp
and then :
python migrate

1.3 - Creating an insert data form

Now we create a file which will be used to generate the insert data form:
# studentsApp/
from django.forms import ModelForm
from studentsApp.models import Students

class StudentsForm(ModelForm):
    class Meta:
        model = Students
        fields = ['name' , 'email' ,'phone' ,'section' , 'photo']
Regarding views and models, they will be created in the same way as the previous tutorial except to add a

1.4 - Creating views for studentsApp
# studentsApp/
from django.http import HttpResponseRedirect
from django.shortcuts import render
from .forms import StudentsForm

def student(request):
    if request.method == 'POST':
        form = StudentsForm(request.POST, request.FILES)
        if form.is_valid():
            return HttpResponseRedirect('/student/')
        form = StudentsForm()
    return render(request, 'student.html', {'form': form})

2 - Pagination system

2.1 - The Paginator class

provides a class called
which performs
. It is located in the
module. The Paginator class is instantiated with two parameters: the list of objects to spread and the maximum number of objects to display per page. So first we have to import it: We start by importing the Paginator class and related classes:
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

  1. The Paginator class is located at:
    . This is a class allowing to paging a list of data with links to first page last page, Previous/Next... 
  2. The EmptyPage class: class used to throw an exception if the page is not found, especially when the indexing limit is exceeded.  
  3. The PageNotInteger class: class used to throw an exception if the index of the requested page is not an integer.

We then create an object:
which contains the student data as a list:
object_list = Students.objects.all()
We then create a
Paginator object
whose parameter will be the object:
and the number of elements per page to display:
paginator = Paginator(object_list, 3)
We then retrieve the number of the current page we are on:
page_number = request.GET.get('page')
We then create exceptions if the requested page is not found, or if the requested page number is not an integer:
     page_object =
 except PageNotAnInteger:
     page_object =
 except EmptyPage:
     page_object =
Here is finally the code of the file:
# studentsApp/
from django.shortcuts import render, redirect
from .forms import StudentsForm
from .models import Students
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

def students(request):
    if request.method=='POST':
        form = StudentsForm(request.POST,request.FILES)
        if form.is_valid():
            return redirect('students')
        form = StudentsForm()
    # Pagination
    object_list = Students.objects.all()
    paginator = Paginator(object_list, 2)
    page_number = request.GET.get('page') # get current page number

        page_object =
    except PageNotAnInteger:
        page_object = # go to page number 1
    except EmptyPage: # except last page
        # stay on current page
        page_object =
    return render(request, 'students.html', {'form': form, 'page_obj': page_object})
Load Pagination system in the template
<!-- Load pagination system -->
<div style="font-size:20px;">
        {% if page_obj.has_previous %}
            <a href="?page=1">« first</a>
            <a href="?page={{ page_obj.previous_page_number }}">previous</a>
        {% endif %}

            Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.

        {% 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 %}
Code final of pagination in the template:
<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
<h2>Manage students </h2>

	<!-- load form -->
    <form enctype="multipart/form-data"  method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="save btn btn−default">Save</button>
<br />

<table border='1' style = 'border-collapse:collapse;' width="600">

         <th>Name</th> <th>Email</th> <th>Phone</th> <th>Section</th> <th>Photo</th>

	<!-- load students data -->
    {% for stud in page_obj %}
<td>{{ }}</td>
<td>{{ }}</td>
<td>{{ }}</td>
<td>{{ stud.section }}</td>
<td width="96"><img src = "/media/{{ }}" width = "96" height = "86"></td>
    {% endfor %}


<!-- Load pagination system -->
<div style="font-size:20px;">
        {% if page_obj.has_previous %}
            <a href="?page=1">« first</a>
            <a href="?page={{ page_obj.previous_page_number }}">previous</a>
        {% endif %}

            Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.

        {% 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><br />



Younes Derfoufi

No comments:

Post a Comment

Learn Python For Beginners

Category Of Mobile Courses

Actualités (644) Adsense (1) Affiliation (1) Algebraic Topology (2) Algorithmic (1) all-news (30) Android (5) Android App (8) Android app without code (4) Android Apps (256) Android Development (4) Android download (2) Android OS (3) AngularJS (1) Automata theory and formal language (5) Bootstrap CSS (1) C programming (5) Category and Functor (8) CMS (3) Computer Glossary (18) Create Mobile App With Ionic Framework (2) CSS (2) CSS-Cascading-Style-Sheets (4) Developpement Java (13) Differential Geometry (1) Django-Python-Framework (15) dropshiping (26) Earn Money by Internet (4) Emplois (23) Framework php (2) Fraud (2) Github (2) HTML (7) IT News (3) Java For Beginners (10) Javascript (12) Kotlin Programming Language (8) Kotlin For Mobile Android (1) Linux Download (2) Marketing (5) Mobile (3) Mobile Courses (4) Mobile Marketing (4) MoneyGram (1) News (721) Node.js (5) Open Source (1) Photoshop (1) Protect Computer (1) Python (36) Python BeautifulSoup (1) Python For Data Science (2) Python PyQt (13) Python Reference (1) Python Source Code (3) Python-Books (6) Python-DVD-Training (1) Python-Exercises (297) Python-Framework (1) Python-IDE (1) Python-Kivy-Framework (2) Python-Modules (1) Python-pdf (2) Python-pyQt (1) python-temp (3) Référencement (2) Script PHP (2) Security (6) SEO (1) Snipping Tool: Faq (1) Social Networks (1) Source Code (4) Statistics With SPSS (2) Surveillance Software (1) Travail à domicile (6) Tutoriels php en vidéos (2) Tutoriels-MySql (6) tutoriels-php (19) Utilitaires (1) VPS (1) Web Hosting (1) Webcam (1) Webmarketing (11) Western Union (1) Windows 10 (1) Windows 7 (4) Windows 7 Faq (2) Windows 8 (1) Windows Accessories (1) Windows Download (8) Windows Drivers (1) Windows Fonts (1) Windows Power Shell (2) Windows Registry (2) Windows Security (18) Windows Software (2) Windows Spyware (2) Windows utilities (3) Windows Virus (2) Windows Vista (3) Windows Wireless (1) Windows xp (1) Wordpress (1)

Sample text

Sample Text

Blogger Templates