etutorialspoint
  • Home
  • PHP
  • MySQL
  • MongoDB
  • HTML
  • Javascript
  • Node.js
  • Express.js
  • Python
  • Jquery
  • R
  • Kotlin
  • DS
  • Blogs
  • Theory of Computation

Django Pagination with Ajax and jQuery

In this article, you will learn how to create simple pagination using Django with Ajax and jQuery.





Sometimes we need to display data on a web page from the server. The data can be long lists. If you list all the data on the same page, it will become more confusing and also have a high page loading time. Pagination is the process of separating a long list of contents into discrete pages.





Django is a free, open-source, Python-based framework. It enables the fast development of any type of web application. It is secure, maintainable, portable, and scalable. The main advantages of using Django are that it fully supports common web development tasks, like administration, authentication, site maps, etc.



As we're going to develop django pagination without refreshing page, if you have not installed the Django package, please follow the Django documentation for initial setup.

AJAX pagination processes the AJAX requests on each link and the client-side code that actually sends the requests. In this article, we are using jQuery to make AJAX requests.



Here, we are creating an empty project 'blog' and a new app 'latestnews'.

(env) c:\python37\Scripts\projects>django-admin startproject blog

(env) c:\python37\Scripts\projects>cd blog

(env) c:\python37\Scripts\projects\blog>django-admin startapp latestnews




settings.py

After creating the app, we need to tell Django we're going to use it. Do this by editing your settings file and changing the INSTALLED_APPS setting to add the name of the module.

INSTALLED_APPS = [
    'latestnews',
]

It is also required to edit the database settings in 'settings.py'.

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'demo',
        'USER': 'root',
        'PASSWORD': '',
        'HOST': 'localhost',
        'PORT': '3306'
    }
}




models.py

The model helps to map the fields to the database. It represents a database table. Here is the model for 'Latestnews' which contains fields title and content.

from django.db import models

# Create your models here.

class Latestnews(models.Model):
    title = models.CharField(max_length=100)
    content= models.CharField(max_length=500)

    class Meta:
        db_table = "latestnews"


views.py

Form data sent back to a Django website is processed with a view, and to handle the form, we need to instantiate it in the view for the URL where we want it to be published. In the 'views.py', we have imported JsonResponse, Paginator, and the Latestnews model. The paginator classes live in django.core.paginator.

from django.shortcuts import render
from django.http import JsonResponse
from django.core.paginator import Paginator
from .models import Latestnews

def display_latestnews(request):
    
    newsdata = Latestnews.objects.all()
    # articles per page
    per_page = 4
    # Paginator in a view function to paginate a queryset
    # show 4 news per page
    obj_paginator = Paginator(newsdata, per_page)
    # list of objects on first page
    first_page = obj_paginator.page(1).object_list
    # range iterator of page numbers
    page_range = obj_paginator.page_range

    context = {
    'obj_paginator':obj_paginator,
    'first_page':first_page,
    'page_range':page_range
    }
    #
    if request.method == 'POST':
        #getting page number
        page_no = request.POST.get('page_no', None) 
        results = list(obj_paginator.page(page_no).object_list.values('id', 'title','content'))
        return JsonResponse({"results":results})

    return render(request, 'index.html',context)




Create Template Files

This HTML file includes the jQuery library and Bootstrap files. We have placed the jQuery coding part at the bottom of the page. When the user clicks on the pagination link, jQuery makes the Ajax requests that display the next page content.

To protect against Cross Site Request Forgeries, we have added the {% csrf_token %} tag to the ajax requests. It adds a hidden input field containing a token that gets sent with each POST request.

index.html

<!DOCTYPE html>
<html>
    <head>
        <title>Pagination in Django</title>
		<style>
		
		.pagination { display: inline-block;}
		.pagination a { color: black; float: left; padding: 8px 16px; text-decoration: none;}
		.pagination a.active { background-color: #4CAF50; color: white;}
		.pagination a:hover:not(.active) {background-color: #ddd;}
		</style>
		<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" crossorigin="anonymous">
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
		<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
    </head>
    <body>
	<div class="container">
		
		<div id="articles">
			{% for i in first_page %}
			<h2>{{i.title}}</h2>
			<p>{{i.content}}</p>
			{% endfor %}	
		</div>
		
		<div class="pagination">
		{% for i in page_range %}
		<a style="margin-left: 5px; " href="{{i}}">{{i}}</a>
		{% endfor %}
		</div>
	</div>
	<script>
	$('a').click(function(event){
		// preventing default actions
		event.preventDefault();
		var page_no = $(this).attr('href');
		// ajax call
			$.ajax({
					type: "POST",
					// define url name
					url: "{% url 'display_pagination' %}", 
					data : {    
					page_no : page_no, 
					csrfmiddlewaretoken: '{{ csrf_token }}',
				},
				// handle a successful response
				success: function (response) {
					$('#articles').html('')
					$.each(response.results, function(i, val) {
					 //append to post
					$('#articles').append('<h2>' + val.title + '</h2><p>'+ val.content +'</p>')
				   });
				},
				error: function () {
					alert('Error Occured');
				}
			}); 
	});    
	</script>
</body>
</html>




urls.py

At last, we have added a path to the route page for the particular link.

from django.contrib import admin
from django.urls import path
from latestnews.views import (
    display_latestnews, 
)

urlpatterns = [
    path('latestnews/', display_latestnews, name="display_pagination"),
]
Django Pagination



Related Articles

Django Export Model Data to CSV
Django Simple File Upload
Display image from database in Django
Generate and download a CSV file in Django
Django bootstrap 4 form template
Django Custom User Model SignUp, Login and Logout
Django serialize queryset into JSON and display in template
Django ajax GET and POST request
How to upload image and add in Django model Imagefield
Python program to convert Celsius to Fahrenheit
Python send mail to multiple recipients using SMTP server
How to generate QR Code in Python using PyQRCode
Python programs to check Palindrome strings and numbers
CRUD operations in Python using MYSQL Connector
Fibonacci Series Program in Python
Python File Handler - Create, Read, Write, Access, Lock File
Python convert XML to JSON
Python convert xml to dict
Python convert dict to xml




Most Popular Development Resources
Retrieve Data From Database Without Page refresh Using AJAX, PHP and Javascript
-----------------
PHP Create Word Document from HTML
-----------------
How to get data from XML file in PHP
-----------------
Hypertext Transfer Protocol Overview
-----------------
PHP code to send email using SMTP
-----------------
How to encrypt password in PHP
-----------------
Characteristics of a Good Computer Program
-----------------
Create Dynamic Pie Chart using Google API, PHP and MySQL
-----------------
PHP MySQL PDO Database Connection and CRUD Operations
-----------------
Splitting MySQL Results Into Two Columns Using PHP
-----------------
Dynamically Add/Delete HTML Table Rows Using Javascript
-----------------
How to get current directory, filename and code line number in PHP
-----------------
How to add multiple custom markers on google map
-----------------
Fibonacci Series Program in PHP
-----------------
Get current visitor\'s location using HTML5 Geolocation API and PHP
-----------------
How to Sort Table Data in PHP and MySQL
-----------------
Submit a form data using PHP, AJAX and Javascript
-----------------
Simple star rating system using PHP, jQuery and Ajax
-----------------
How to generate QR Code in PHP
-----------------
jQuery loop over JSON result after AJAX Success
-----------------
Simple pagination in PHP
-----------------
Recover forgot password using PHP7 and MySQLi
-----------------
PHP MYSQL Advanced Search Feature
-----------------
PHP Server Side Form Validation
-----------------
PHP user registration and login/ logout with secure password encryption
-----------------
Simple PHP File Cache
-----------------
jQuery File upload progress bar with file size validation
-----------------
Simple File Upload Script in PHP
-----------------
Simple way to send SMTP mail using Node.js
-----------------
Php file based authentication
-----------------
To check whether a year is a leap year or not in php
-----------------
PHP User Authentication by IP Address
-----------------
Calculate distance between two locations using PHP
-----------------
How to print specific part of a web page in javascript
-----------------
PHP Secure User Registration with Login/logout
-----------------
Simple Show Hide Menu Navigation
-----------------
Detect Mobile Devices in PHP
-----------------
Polling system using PHP, Ajax and MySql
-----------------
PHP Sending HTML form data to an Email
-----------------
Google Street View API Example
-----------------
SQL Injection Prevention Techniques
-----------------
Get Visitor\'s location and TimeZone
-----------------
Driving route directions from source to destination using HTML5 and Javascript
-----------------
Convert MySQL to JSON using PHP
-----------------
Preventing Cross Site Request Forgeries(CSRF) in PHP
-----------------
Set and Get Cookies in PHP
-----------------
PHP Programming Error Types
-----------------
CSS Simple Menu Navigation Bar
-----------------
Date Timestamp Formats in PHP
-----------------
How to add google map on your website and display address on click marker
-----------------
How to select/deselect all checkboxes using Javascript
-----------------
Write a python program to print all even numbers between 1 to 100
-----------------
How to display PDF file in web page from Database in PHP
-----------------
PHP Getting Document of Remote Address
-----------------
File Upload Validation in PHP
-----------------


Most Popular Blogs
Most in demand programming languages
Best mvc PHP frameworks in 2019
MariaDB vs MySQL
Most in demand NoSQL databases for 2019
Best AI Startups In India
Kotlin : Android App Development Choice
Kotlin vs Java which one is better
Top Android App Development Languages in 2019
Web Robots
Data Science Recruitment of Freshers - 2019


Interview Questions Answers
Basic PHP Interview
Advanced PHP Interview
MySQL Interview
Javascript Interview
HTML Interview
CSS Interview
Programming C Interview
Programming C++ Interview
Java Interview
Computer Networking Interview
NodeJS Interview
ExpressJS Interview
R Interview


Popular Tutorials
PHP Tutorial (Basic & Advance)
MySQL Tutorial & Exercise
MongoDB Tutorial
Python Tutorial & Exercise
Kotlin Tutorial & Exercise
R Programming Tutorial
HTML Tutorial
jQuery Tutorial
NodeJS Tutorial
ExpressJS Tutorial
Theory of Computation Tutorial
Data Structure Tutorial
Javascript Tutorial






Learn Popular Language

listen
listen
listen
listen
listen

Blogs

  • Jan 3

    Stateful vs Stateless

    A Stateful application recalls explicit subtleties of a client like profile, inclinations, and client activities...

  • Dec 29

    Best programming language to learn in 2021

    In this article, we have mentioned the analyzed results of the best programming language for 2021...

  • Dec 20

    How is Python best for mobile app development?

    Python has a set of useful Libraries and Packages that minimize the use of code...

  • July 18

    Learn all about Emoji

    In this article, we have mentioned all about emojis. It's invention, world emoji day, emojicode programming language and much more...

  • Jan 10

    Data Science Recruitment of Freshers

    In this article, we have mentioned about the recruitment of data science. Data Science is a buzz for every technician...

Follow us

  • etutorialspoint facebook
  • etutorialspoint twitter
  • etutorialspoint linkedin
etutorialspoint youtube
About Us      Contact Us


  • eTutorialsPoint©Copyright 2016-2023. All Rights Reserved.