Handling Ajax request in Django
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).

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.
Now you will have file structure similar to this:

2. Create Models
In postapp/models.py, define two models: Post and Like.
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:
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:
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:
<!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:
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:

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:
