Open In App

Handling Ajax request in Django

Last Updated : 15 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

AJAX (Asynchronous JavaScript and XML) is a web development technique that allows a web page to communicate with the server without reloading the entire page. In Django, AJAX is commonly used to enhance user experience by sending and receiving data in the background using JavaScript (or libraries like jQuery).

Block diagram of working of ajax

In this tutorial, we’ll build a simple post-liking app where users can like a post via an AJAX request without refreshing the page.

1. Initialize the Django Project and App

Make sure Django is installed. Then run:

django-admin startproject post

cd post

python manage.py startapp postapp

Add 'post' to your INSTALLED_APPS in post/settings.py.

INSTALLED_APPS

Now you will have file structure similar to this:

djano_fs_01
file structure of the project

2. Create Models

In postapp/models.py, define two models: Post and Like.

Python
from django.db import models

class Post(models.Model):
    post_heading = models.CharField(max_length=200)
    post_text = models.TextField()

    def __str__(self):  # Use __unicode__ if Python 2
        return self.post_heading

class Like(models.Model):
    post = models.ForeignKey(Post, on_delete=models.CASCADE)

Then run the migration commands to create the database:

python manage.py makemigrations
python manage.py migrate

3. Create Views 

In postapp/views.py:

Python
from django.shortcuts import render
from django.http import HttpResponse
from .models import Post, Like

def index(request):
    posts = Post.objects.all()
    return render(request, 'post/index.html', {'posts': posts})

def likePost(request):
    if request.method == 'GET':
        post_id = request.GET['post_id']
        liked_post = Post.objects.get(pk=post_id)
        Like.objects.create(post=liked_post)
        return HttpResponse("Liked!")
    return HttpResponse("Invalid request.")

4. Set Up URLs

In post/urls.py:

Python
from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('post.urls')),
]

5. Template and AJAX Request

Create the file post/templates/post/index.html:

HTML
<!DOCTYPE html>
<html>
<head>
    <title>Like Post App</title>
</head>
<body>
    <p id="message"></p>
    {% for post in posts %}
        <h3>{{ forloop.counter }}) {{ post.post_heading }}</h3>
        <p>{{ post.post_text }}</p>
        <a class="likebutton" id="like{{ post.id }}" href="#" data-catid="{{ post.id }}">Like</a>
    {% endfor %}

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
    <script>
        $('.likebutton').click(function(e){
            e.preventDefault();
            var postId = $(this).data("catid");
            $.ajax({
                type: "GET",
                url: "/likepost/",
                data: {
                    post_id: postId
                },
                success: function(data) {
                    $('#like' + postId).remove();
                    $('#message').text(data);
                }
            });
        });
    </script>
</body>
</html>

When the "Like" link is clicked, it sends a GET request to /likepost/?post_id=<id>, and the like count is updated in the background without refreshing the page.

6. Register Models in Admin 

In postapp/admin.py:

Python
from django.contrib import admin
from .models import Post, Like

admin.site.register(Post)
admin.site.register(Like)

Running the App

We can check the working of the app by creating a superuser by running the following command:

python manage.py createsuperuser

You’ll be prompted to enter a username, email, and password, after entering those credentials the superuser will be created and now we can run the app using command:

python manage.py runserver

Visit http://127.0.0.1:8000/admin/, log in with your superuser credentials, and add a few posts under the Post model.

Outputs:

django07
Snapshot of creating a post

In the above snapshot we can see that we have created a new post with heading and text. After creating posts we can like them:

django08
Snapshot of liking the post

Next Article
Article Tags :
Practice Tags :

Similar Reads