Django Ajax Pagination Example Tutorial

Hi Dev,
Today our leading topic is django ajax pagination example tutorial. This tutorial will give you simple example of how to use django pagination with ajax and jquery. this example will help you how to create pagination using jquery and ajax in django. I explained simply step by step django ajax pagination example. So, let's follow few step to create example of django pagination with ajax and jquery.
Each link's AJAX request and the client-side code that initiates the requests are processed by AJAX pagination. JQuery is being used in this post to do AJAX requests.
Here i explained simply step by step example of how to how to create pagination using ajax in django.
Step 1: Create a Project
In this step, we’ll create a new django project using the django-admin. Head back to your command-line interface and run the following command:
django-admin startproject example
Step 2: Create a App
Now we'll create a single app called core to store a list of post names. We're keeping things intentionally basic. Stop the local server with Control+c and use the startapp command to create this new app.
python3 manage.py startapp core
Step 3: Update setting.py
Then update INSTALLED_APPS within our settings.py file to notify Django about the app, in setting.py file so our setting file look like this..
settings.py.... INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'core', ]Step 4: Create a Model
Now go for the models we will We'll call our single model Post and it will have just one fields: title. And finally set __str__ to display the name of the article in admin interface.
core/models.pyfrom django.db import models # Create your models here. class Article(models.Model): title = models.CharField(max_length=300) def __str__(self): return self.title
Ok, all set. We can engender a migrations file for this change, then integrate it to our database via migrate.
python manage.py makemigrations python manage.py migrate
Step 5: Creating the Views
In this step, we need to configure views. The home page will just be a template. function is basically get the all object of article table open the core/views.py file and add:
core/views.pyfrom django.shortcuts import render from .models import Article from django.http import JsonResponse from django.core.paginator import Paginator # Create your views here. def pagination_ajax(request): my_model = Article.objects.all() number_of_item = 5 paginatorr = Paginator(my_model, number_of_item) first_page = paginatorr.page(1).object_list page_range = paginatorr.page_range context = { 'paginatorr':paginatorr, 'first_page':first_page, 'page_range':page_range } if request.method == 'POST': page_n = request.POST.get('page_n', None) results = list(paginatorr.page(page_n).object_list.values('id', 'title')) return JsonResponse({"results":results}) return render(request, 'index.html',context)
Step 6: Creating the Templates
Next, then with your text editor create new templates files: core/templates/index.html file and the add:
core/templates/index.html<!DOCTYPE html> <html> <head> <title>Tuts-Station.com</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.2.1/css/bootstrap.min.css" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.2.1/js/bootstrap.min.js"></script> <style> body{ background-color: #f7fcff; } .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> </head> <body> <div class="container mt-5 pt-5"> <div class="row d-flex justify-content-center"> <div class="col-md-8"> <div class="card"> <div class="card-header"> <h4>Django Ajax Pagination Example Tutorial - <span class="text-primary">Tuts-Station.com</span></h4> </div> <div class="card-body"> <table class="table table-bordered"> <thead> <tr> <th>Title</th> </tr> </thead> <tbody id="articles"> {% for i in first_page %} <tr> <td>{{i.title}}</td> </tr> {% endfor %} </tbody> </table> <div class="pagination"> {% for i in page_range %} <a style="margin-left: 5px;" class="ajax-pag" href="{{i}}">{{i}}</a> {% endfor %} </div> </div> </div> </div> </div> </div> <script> $('.ajax-pag').click(function(event){ event.preventDefault(); var page_n = $(this).attr('href'); $.ajax({ type: "POST", url: "{% url 'pagination_ajax' %}", data : { page_n : page_n, csrfmiddlewaretoken: '{{ csrf_token }}', }, success: function (response) { $('#articles').html('') $.each(response.results, function(i, val) { $('#articles').append('<tr><td>' + val.title + '</td></tr>') }); }, error: function () { alert('Error Occured'); } }); }); </script> </body> </html>
Step 7: Creating URLs
In this section, we need a urls.py file within the core app however Django doesn't create one for us with the startapp command. Create core/urls.py with your text editor and paste below code.
core/urls.pyfrom django.urls import path from . import views urlpatterns = [ path('pagination', views.pagination_ajax,name='pagination_ajax'), ]
Next, we require to add a URL path for our example app which can be done by importing include and setting a path for it.
example/urls.pyfrom django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('core.urls')), ]
Run the Server
In this step, we’ll run the local development server for playing with our app without deploying it to the web.
python manage.py runserver
Next, go to the http://localhost:8000/pagination address with a web browser.
I hope it will help you....
Happy Coding!