Open In App

Handling Ajax request in Django

 

Introduction 

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.

Glossary

Implementation: 

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

$ django-admin startproject django_example
$ cd django_example
$ python manage.py startapp post 

 

 

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

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)
class Like(models.Model):
    post = models.ForeignKey(Post, on_delete = models.CASCADE)
$ python manage.py makemigrations
$ python manage.py 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 views.py 

from .models import Post, Like
from django.http import HttpResponse
def index(request):
    posts = Post.objects.all()  # Getting all the posts from database
    return render(request, 'post/index.html', { 'posts': posts })
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
           m.save()  # saving it to store in database
           return HttpResponse("Success!") # Sending an success response
    else:
           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/urls.py. Your django_example/urls.py should look something like this:

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

To create URLs, create file post/urls.py. Your post/urls.py 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: 

<!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 type="text/javascript">
    $('.likebutton').click(function(){
    var catid;
    catid = $(this).attr("data-catid");
    $.ajax(
    {
        type:"GET",
        url: "/likepost",
        data:{
                 post_id: catid
        },
        success: function( data ) 
        {
            $( '#like'+ catid ).remove();
            $( '#message' ).text(data);
        }
     })
});
</script>
</body>
</html>
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: 

from .models import Post, Like
admin.site.register(Post)
admin.site.register(Like)

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.

Article Tags :