How to Integrate Ajax with Django applications

AJAX is a way of exchanging data with a server, without refreshing or reloading the webpage. It is the art of making web development more dynamic and interactive. Using ajax we can request data from the server before or after page load and update parts of web pages.

How to Integrate Ajax with Django applications

In this tutorial, we are going to learn how to use AJAX with Django to make web applications more fast and dynamic. We will send AJAX request and using Django AJAX Response we will update the web page. For this tutorial, I am using JQuery. You can also handle AJAX with Django libraries like django-dajax or Javascript. But the concept of working with AJAX request with Django will be the same.

Initial Setup of Application for Ajax Request

Learn from here how to Create/Initiate Django Project using Virtual Env.

I am using base.html for extending templates. Here is my base.html Django template looks like:

base.html

{% load static %}
<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>{% block title %}Title{% endblock title %}</title>
    {% block stylesheet %}{% endblock stylesheet %}
  </head>
  <body>
    <main>
    {% block content %}
    {% endblock content %}
    </main>
    <script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
    {% block javascript %}
    {% endblock javascript%}
  </body>
</html>

All the page-specific content, javascript, and CSS go inside the respective blocks. I have also added the JQuery library above javascript block.

Simple Scenario For Validating Username Existence using Ajax and Django

Let’s take a simple Django Ajax example for validating username exists in the database. User will enter username and ajax call will be gone to the server to check whether the username is already taken or not.

Views.py

from django.views.generic.edit import CreateView
from django.contrib.auth.forms import UserCreationForm

class UserSignUpView(CreateView):
    form_class = UserCreationForm
    template_name = "signup.html"

Urls.py

from django.urls import path
from simple_ajax_app.views import UserSignUpView

urlpatterns = [
    path('simpleajax/', UserSignUpView.as_view(), name='simple_ajax'),         
]

signup.html

{% extends 'base.html' %}

{% block content %}
<h1>Simple Ajax Django Example</h1>
<form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Sign up</button>
</form>
{% endblock %}

On browser it will look like this – Eg – http://localhost:8000/simpleajax/

Simple Django Ajax Request

If you are getting error Error – TemplateDoestNotExists – then you might not set your template paths. For settings template path you need to edit your settings.py file. There you should find TEMPLATES list. In that change – 'DIRS': [], to 'DIRS': [BASE_DIR + '/templates/',],

Ajax Request

Lets handle the Asynchronous Request for finding username existence.

First, let’s inspect the username input field which is generated by the {{ form.as_p }} in signup.html.

<input type="text" name="username" id="id_username" maxlength="150" autofocus="" required="">

The reason for inspecting is to find out the input field id, which is id_username.

Now let’s create a listener for the username field change event:

{% extends 'base.html' %}

{% block javascript %}
  <script>
    $("#id_username").change(function () {
      console.log( $(this).val() );
    });
  </script>
{% endblock %}

{% block content %}
  <form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Sign up</button>
  </form>
{% endblock %}

The reason for console.log is to check whether the listener is working properly. You can check out the output in your console. It is always good to, trail and then plays.

Let’s create a view for checking if the username exists in our database and which will return a JSON Response

Views.py

from django.contrib.auth.models import User
from django.views.generic.edit import View
from django.http import JsonResponse

class ValidateUsername(View):
    def get(self, request):
        username = request.GET.get('username', None)
        data = {
            'is_present': User.objects.filter(username__iexact=username).exists()
        }
        return JsonResponse(data)

Now lets create a route URL for that view

Urls.py

from django.urls import path
from simple_ajax_app.views import UserSignUpView, ValidateUsername

urlpatterns = [
    path('simpleajax/', UserSignUpView.as_view(), name='simple_ajax'),
    path('ajax/validate-username/', ValidateUsername.as_view(), name='simple_ajax_validate'),
]

And now we will add Ajax in signup.html

signup.html

{% extends 'base.html' %}

{% block javascript %}
<script>
    $("#id_username").change(function () {
        var username = $(this).val();

        $.ajax({
            url: '/ajax/validate-username/',
            // url: '{% url 'simple_ajax_validate' %}',
            data: {
                'username': username
            },
            dataType: 'json',
            success: function (data) {
                if (data.is_present) {
                    alert("A user with this username already exists.");
                }
            }
        });

    });
</script>
{% endblock javascript%}

{% block content %}
<h1>Simple Ajax Django Example</h1>
<form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Sign up</button>
</form>
{% endblock %}

Done. Now, let’s check our Ajax Request on Browser – http://localhost:8000/simpleajax/

If username exists then it will prompt a dialog box which will say, Username Already Exists.

It’s also available on GitHub – https://github.com/studygyaan/how-to-integrate-ajax-with-django-applications

Share