In this tutorial, I will be showing you the practical code example for how to send and handle ajax requests from the frontend to the django backend.
Let's get started by creating a new django project.
django-admin startproject demoproject
cd demoproject
python manage.py startapp demoapp
Now, add the new demoapp to INSTALLED_APPS list inside the settings.py file
INSTALLED_APPS = [
'demoapp',
]
For the demonstration, I'll be creating a simple Blog model with only two basic fields(title, content).
from django.db import models
class Blog(models.Model):
title = models.CharField(max_length=50)
content = models.TextField()
def __str__(self):
return self.title
Register the blog model with the admin.
from django.contrib import admin
from demoapp.models import Blog
admin.site.register(Blog)
To easily accept and handle the user input let's create the model form for our Blog model.
from django.forms import ModelForm
from demoapp.models import Blog
class BlogForm(ModelForm):
class Meta:
model = Blog
fields = "__all__"
python manage.py makemigrations
python manage.py migrate
from django.shortcuts import render
from demoapp.forms import BlogForm
from django.http import JsonResponse
def create_blog(request):
form = BlogForm()
return render(request, "demoapp/create_blog.html", {"form": form})
def ajax_form(request):
if request.method == "POST":
form = BlogForm(request.POST)
if form.is_valid():
form.save()
return JsonResponse({"msg": 'Success'})
return JsonResponse({"msg": 'Invalid Data'}, status=201)
return JsonResponse({"msg": 'Method Not Allowed'}, status=405)
Here I have created two views.
create_blog: This simply returns the create_blog HTML template rendering the blog creation form in the frontend.
ajax_form: It is the view to which we'll send our ajax request. It first checks If the request type is POST(else it returns a 405 response). Then it validates the user input and creates the blog and returns the 200 response.
Let's create the urls for our views.
from django.contrib import admin
from django.urls import path
from demoapp import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.create_blog, name='create_blog'),
path('ajax/', views.ajax_form, name='ajax_form'),
]
It finally the time to create a html template that sends a ajax request to our backend.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Create Blog</title>
</head>
<body>
<form method="POST" id="form">
{{ form.as_p }}
{% csrf_token %}
<input type="submit" value="submit">
</form>
<!-- Ajax Javascript Goes Here -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script></script>
</body>
</html>
Above is just a simple HTML template with the form and empty script tag.
Here I will use the jquery library to send the ajax requests. But you can also use something else like Axios, Fetch api, or XMLHttpRequest.
<!-- Ajax Javascript Goes Here -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script>
let form = $("#form")
form.on("submit", function(event){
event.preventDefault();
$.ajax({
url: "{% url 'ajax_form' %}",
method: "POST",
data: form.serialize(),
dataType: 'json',
success: function (data) {
if(data.msg === 'Invalid Data'){
alert("Error")
}
else{
alert("Success")
}
}
})
})
</script>
Here we created the event listener on our form submission. So when the user submits the form we'll send the post request to the backend and display an alert showing "Success" or "Error" based on the response from the server.
Finally, Let's spin up our django development server to check if everything is working fine.
python manage.py runserver