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.
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.
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"),
]
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')
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 %}<div class="col-lg-4"><form method="POST" enctype="multipart/form-data">{% csrf_token %}<input type="text" class="form-control mb-3" id="username" placeholder="Username"><input type="password" class="form-control mb-3" placeholder="Password"><input type="password" class="form-control mb-3" placeholder="Repeat Password"><input type="button" value="Submit" class="btn btn-primary"></form></div>{% endblock %}
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.
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");
}
}
});
});
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.
Thanks for reading.
Adios!
Free Resources