How to work with AJAX requests and responses in Django

Share

There are a lot of scenarios where we want to use AJAX requests in web applications as it helps web applications to be much faster and dynamic. This shot will explore how we can handle AJAX requests and responses in Django to create a username validator. We will be using function-based views and jQuery for simplicity.

Without wasting any more time, let’s jump to the interesting part.

Initial set-up

1. base.html

base.html is the base file that will be extended in other templates. By using this approach, we can ignore installing CDNs in every template we create.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AJAX example</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" >
</head>
<body>
    {% block content %}
    {% endblock %}
    <script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
    <script src="{% static 'js/app.js' %}"></script>
</body>
</html>

As mentioned, for this shot, let’s assume we want to validate the username field as soon as the user enters his username. We will do a simple check to see whether or not someone has already taken the username.

2. urls.py

The urls.py file contains the URLs that will be served in our web application.

from django.urls import path
from . import views

urlpatterns = [
    path('',views.index,name="index"),
]

3. views.py

The views.py file contains the various methods used to serve data through the URLs defined in our web application.

from django.shortcuts import render
from django.http import HttpResponse

def index(request):
    return render(request,'register.html')

4. register.html

The register.html file contains the UI part. There is a form that contains three input fields, and one submit button. Make sure to include the csrf_token inside the form.

{% extends 'base.html' %}

{% block content %}![](/api/edpresso/shot/5130344753266688/image/4876611641409536)![](/api/edpresso/shot/5130344753266688/image/5158721535082496)
<div>
<form method="POST" enctype="multipart/form-data">
    {% csrf_token %}
    <input type="text" id="username" placeholder="Username">
    <input type="password" placeholder="Password">
    <input type="password" placeholder="Repeat Password">
    <input type="button" value="Submit">
</form>
</div>
{% endblock %}

UI


AJAX Request

Let’s implement an AJAX request to check whether or not the username is already taken. We will use the id of the username field and add a listener for its change event.

1. app.js

The change event occurs every time the value of the username field changes. Make sure the event is getting fired correctly, and you got the listener right. The AJAX request uses the POST method here (you can use any according to your need).

$("#username").change(function () {
        var username = $(this).val();
        $.ajaxSetup({
            headers: {
                "X-CSRFToken": document.querySelector('[name=csrfmiddlewaretoken]').value,
            }
        });
        $.ajax({
        url: 'validate',
        method: 'POST',
        data: {
          'username': username
        },
        dataType: 'json',
        success: function (data) {
          if (data.taken) {
            alert("Username taken");
          }
        }
      });
    });

2. urls.py and views.py

Let’s add the respective URL and method to urls.py and views.py, below.

from django.urls import path
from . import views

urlpatterns = [
    path('',views.index,name="index"),
    path('validate',views.validate,name="validate"),
]
from django.contrib.auth.models import User

def validate(request):
    username = request.POST['username']
    data = {
        'taken' : User.objects.filter(username__iexact=username).exists()
    }
    return JsonResponse(data)

That was it1 Now, you have learned how to handle AJAX requests in Django. You can also do this using Vanilla JavaScript, the only thing that would be slightly different is app.js.

You can connect with me on Twitter for any discussions.

Thanks for reading.

Adios!

Attributions:
  1. undefined by undefined