Skip to content
Related Articles
Open in App
Not now

Related Articles

Handling Ajax request in Django

Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 06 May, 2022
Improve Article
Save Article



This tutorial explains how to carry out an ajax request in the Django web framework. We will create a simple post-liking app as a part of the example.


  • Project Initialization
  • Create models
  • Create views
  • Write URLs
  • Carry out a request with Jquery Ajax.
  • Register models to admin and add some posts.


1. Initiate the Django Project – Here I am assuming that you are done with Django Installation.

  • To Create a Django Project execute: 
$ django-admin startproject django_example
  • After creating a project we need to create a Django app. To create an app say “post” execute the following: 
$ cd django_example
$ python startapp post 
  • Go to django_example/ add the post-app


  • Now you will have files something like this:
Handling Ajax request in Django


2. Create models: To create models, go to the post directory and open 

  • In First, create a post table. To create a post table you’ll need to write:
class Post(models.Model):
    post_heading = models.CharField(max_length=200)
    post_text = models.TextField()
        def __unicode__(self):      # If python2 use __str__ if python3
                return unicode(self.post_heading)
  • Then In, create like a table. To create like a table you’ll need to write:
class Like(models.Model):
    post = models.ForeignKey(Post, on_delete = models.CASCADE)
  • Make Migration and migrate step: 
$ python makemigrations
$ python migrate

After completing these steps, we have our database tables ready to use. 

3. Create Views: 

To create views, we need to go to the post directory and open 

  • First, import Previously created Models and HTTP response
from .models import Post, Like
from django.http import HttpResponse
  • Create an index view to render all the posts. Code sample:
def index(request):
    posts = Post.objects.all()  # Getting all the posts from database
    return render(request, 'post/index.html', { 'posts': posts })
  • Create like posts view to like a post. This view will be called when we will hit a “like button”. Code sample:
def likePost(request):
    if request.method == 'GET':
           post_id = request.GET['post_id']
           likedpost = Post.objects.get(pk=post_id) #getting the liked posts
           m = Like(post=likedpost) # Creating Like Object
   # saving it to store in database
           return HttpResponse("Success!") # Sending an success response
           return HttpResponse("Request method is not a GET")

Once our view gets created we will move to write a template and jQuery to perform an ajax request.

4. Create URLs:

To create URLs, open django_example/ Your django_example/ should look something like this:

from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
     url(r'^', include('post.urls')),   # To make post app available at /

To create URLs, create file post/ Your post/ should look something like this: 

from django.conf.urls import url
from . import views
urlpatterns = [
        url(r'^$', views.index, name='index'),  # index view at /
        url(r'^likepost/$', views.likePost, name='likepost'),   # likepost view at /likepost

5. Making templates and carrying out ajax requests: 

  • Create a file post/templates/post/index.html. Code sample:
<!DOCTYPE html>
    <title>Like Post App</title>
    <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{{}}" href="#" data-catid="{{ }}">Like</a>
    {% endfor %}
    <script src=""></script>
    <script type="text/javascript">
    var catid;
    catid = $(this).attr("data-catid");
        url: "/likepost",
                 post_id: catid
        success: function( data ) 
            $( '#like'+ catid ).remove();
            $( '#message' ).text(data);
Basically, what we are doing here is - we are making an ajax get request -> /likepost?post_id=<id_of_liked_post>

6. To Register models to admin and add some posts: 

  • Open post/
  • Import Models to
from .models import Post, Like
  • Register your models:

Now add some posts using the Django default admin portal. Visit http://localhost:8000/ to view and like posts. I also have added this sample app to my github which you may use for reference.

This blog is written by Anshul Singhal.

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!