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"),
]
Related Articles
Django Export Model Data to CSVDjango 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