![]() |
VOOZH | about |
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.
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:
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
In postapp/views.py:
In post/urls.py:
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.
In postapp/admin.py:
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: