Django Ajax GET Request Example Tutorial

Published On: 17/08/2022 | Category: Django


Hi Dev,

In this tutorial, you will learn django ajax get request example. you will learn how do i get with jquery/ajax in django. I would like to show you jquery ajax get json response example. This tutorial will give you simple example of how do i get data from my ajax get to my django view.

Now let's move on to the GET request. In our current scenario we have to add a like system in created post with ajax GET request.

Here i explained simply step by step example of django ajax get request example.

Step 1: Create a Project

In this step, we’ll create a new django project using the django-admin. Head back to your command-line interface and run the following command:

django-admin startproject example
Step 2: Create a App
python3 manage.py startapp core
Step 3: Update setting.py

In this step we require to do add installed apps in our settings.py file. Add the below lines to your settings.py file:

Next, you need to add it in the settings.py file as follows:


....
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'core',
]
Step 4: Create a Model

In this step we will require the database model for storing employee details data.Open the core/models.py file and add the following code:

core/models.py
from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=250)
    description = models.TextField()
    published = models.DateField(auto_now_add=True)

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

After creating these model, you need to create migrations using the following command:

Next, you need to migrate your database using the following command:

python manage.py makemigrations
python manage.py migrate
Step 5: Creating the Views

In this step, we need to create the views for performing fetch record to the database.Open the core/views.py file and add:

core/views.py
from .models import Post, Like
from django.http import HttpResponse

# Create your views here.
def index_view(request):
    posts = Post.objects.all()  # Getting all the posts from database
    return render(request, 'index.html', { 'posts': posts })

def likePost(request):
    if request.method == 'GET':
        post_id = request.GET['post_id']
        likedpost = Post.objects.get(pk=post_id)
        m = Like(post=likedpost)
        m.save()
        return HttpResponse("You have like this post!")
    else:
        return HttpResponse("Request method is not a GET")
Step 6: Creating the Templates

Next, open the core/templates/index.html file and the add:

<!DOCTYPE html>
<html>
<head>
    <title>Tuts-Station.com</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />
</head>
<body>
    <div class="container mt-5 pt-5">
        <div class="row d-flex justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">
                        <h3>Django Ajax Get Request Example Tutorial - <span class="text-primary">Tuts-Station.com</span></h3>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-12">
                                <div class="alert alert-success message" style="display:none;"></div>
                            </div>
                            <div class="col-md-12">
                                {% for post in posts %}
                                <h3>{{ forloop.counter }}) {{ post.title }}</h3>
                                <p>{{ post.description }} </p>
                                <a class="likebutton" id="like{{post.id}}" href="#" data-catid="{{ post.id }}"><i class="fa fa-thumbs-up" aria-hidden="true"></i> Like</a>
                                {% endfor %}
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script type="text/javascript">

    /*------------------------------------------
    --------------------------------------------
    Like Post 
    --------------------------------------------
    --------------------------------------------*/
    $('.likebutton').click(function(){
        var catid = $(this).attr("data-catid");

        $.ajax({
            type:"GET",
            url: "{% url 'likepost' %}",
            data:{
                post_id: catid
            },
            success: function( data ) 
            {
                $( '.message' ).css('display','block');
                $( '#like'+ catid ).remove();
                $( '.message' ).text(data);
            }
        })
});
</script>
</body>
</html>
Step 7: Creating URLs

In this section, we’ll create the urls to access our CRUD views.Go to the urls.py core/urls.py file and update it as follows:

core/urls.py
from django.urls import path
from .views import postStore, indexView

urlpatterns = [
    path('', index_view, name="index"),
    path('likepost/', likePost, name="likepost"),
]

Next, we will require the modify the urls.py your root preoject folder lets update the file.

example/urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('core.urls')),
]
Run the Server

In this step, we’ll run the local development server for playing with our app without deploying it to the web.

python manage.py runserver

Next, go to the http://localhost:8000/ address with a web browser.

Output

I Hope It will help you....