VOOZH about

URL: https://www.geeksforgeeks.org/python/handling-ajax-request-in-django/

⇱ Handling Ajax request in Django - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Handling Ajax request in Django

Last Updated : 23 Jul, 2025

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).

👁 Image
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.

👁 Image
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.

Then run the migration commands to create the database:

python manage.py makemigrations
python manage.py migrate

3. Create Views 

In postapp/views.py:

4. Set Up URLs

In post/urls.py:

5. Template and AJAX Request

Create the file post/templates/post/index.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:

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
Comment
Article Tags: