Django Ajax Post Request Example

Published On: 23/07/2022 | Category: Django Python

Hi Dev,

In this tutorial, you will learn django ajax post request example. In this article, we will implement a how do i post with jquery/ajax in django. I explained simply about jquery ajax post json response example. it's simple example of how do i get data from my ajax post to my django view. follow bellow step for how to work with ajax in django.

A POST request is consequential in doing things in AJAX, because with a POST request, you can perform a dynamic number of functions, including posting data to a database (or storing data to a database), editing subsisting data in a database, and expunging data from a database. Along with the GET request, you can perform any type of function needed in AJAX

Here i explained simply step by step example of django ajax post request example.

Step 1 : Create a Project

In this step, we’ll create a new django project using the django-admin. Head back to your command-line interface and run the following command:

django-admin startproject example
Step 2 : Create a App
python3 startapp core
Step 3 : Update

In this step we require to do add installed apps in our file. Add the below lines to your file:

Next, you need to add it in the file as follows:

Step 4: Create a Form

In this step we will require the create a formclass for some adding bootstrap class and add button.Open the core/ file and add the following code:

from django import forms
from .models import Employee

class EmployeeForm(forms.ModelForm):
    firstname = forms.CharField(
                "placeholder": "First Name",
                "class": "form-control"
    lastname = forms.CharField(
                "placeholder": "Last Name",
                "class": "form-control"

    class Meta:
        model = Employee
        fields = ("__all__")
Step 5: Create a Model

In this step we will require the database model for storing employee details data.Open the core/ file and add the following code:

from django.db import models

class Employee(models.Model):
    firstname = models.CharField(max_length=255)
    lastname = models.CharField(max_length=255)

After creating these model, you need to create migrations using the following command:

Step 6 : Create a Migrations
python makemigrations

After successfully run the above command go to the core/migrations/

# Generated by Django 3.1.7 on 2022-07-22 10:47

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('core', '0005_remove_photo_description'),

    operations = [
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('firstname', models.CharField(max_length=255)),
                ('lastname', models.CharField(max_length=255)),

Next, you need to migrate your database using the following command:

python migrate
Step 7 : Creating the Views

In this step, we need to create the views for performing fetch record to the database.Open the core/ file and add:

from django.shortcuts import render
from .forms import EmployeeForm
from django.conf import settings
from .models import Employee
from django.http import JsonResponse
from django.core import serializers

# Create your views here.

def indexView(request):
    form = EmployeeForm()
    employees = Employee.objects.all()
    return render(request, "index.html", {"form": form, "employees": employees})

def postStore(request):
    # request should be ajax and method should be POST.
    if request.method == "POST":
        # get the form data
        form = EmployeeForm(request.POST)

        if form.is_valid():
            instance =
            ser_instance = serializers.serialize('json', [ instance, ])
            return JsonResponse({"instance": ser_instance}, status=200)
            # some form errors occured.
            return JsonResponse({"error": form.errors}, status=400)

    return JsonResponse({"error": ""}, status=400)
Step 8 : Creating the Templates

Next, open the core/templates/index.html file and the add:

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <link rel="stylesheet" href="[email protected]/dist/css/bootstrap.min.css">
    <script src=""></script>
    <div class="container mt-5">
        <div class="row d-flex justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">
                        <h3>Django Ajax Post Request Example -</h3>
                    <div class="card-body">
                        <form id="form-submit">
                            <div class="row">
                                <div class="col-md-12">
                                    {% csrf_token %}
                                    {{ form }}
                                    <button type="submit" class="btn btn-primary mt-2"> Submit</button>
        <div class="row d-flex justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">
                        <h3>Employee List</h3>
                    <div class="card-body">
                        <table class="table table-striped table-sm" id="my_friends">
                                    <th>First name</th>
                                    <th>Last name</th>
                            {% for employee in employees %}
                            {% endfor %}
    $("#form-submit").submit(function (e) {
        var serializedData = $(this).serialize();
            type: 'POST',
            url: "{% url 'post_store' %}",
            data: serializedData,
            success: function (response) {

                var instance = JSON.parse(response["instance"]);
                var fields = instance[0]["fields"];
                $("#my_friends tbody").prepend(
            error: function (response) {
Step 9 : Creating URLs

In this section, we’ll create the urls to access our CRUD views.Go to the core/ file and update it as follows:

from django.urls import path
from .views import postStore, indexView

urlpatterns = [
    path('form/', indexView, name="indexView"),
    path('form-store/', postStore, name="post_store"),

Next, we will require the modify the your root preoject folder lets update the file.

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('', include('core.urls')),
Run the Server

In this step, we’ll run the local development server for playing with our app without deploying it to the web.

python runserver

Next, go to the http://localhost:8000/cores address with a web browser.

I Hope It will help you....