Django Ajax Post Request Example

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 ProjectIn 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 exampleStep 2 : Create a App
python3 manage.py startapp coreStep 3 : Update setting.py
In this step we require to do add installed apps in our settings.py file. Add the below lines to your settings.py file:
Next, you need to add it in the settings.py file as follows:
.... INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'core', ]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/forms.py file and add the following code:
core/forms.pyfrom django import forms from .models import Employee class EmployeeForm(forms.ModelForm): firstname = forms.CharField( widget=forms.TextInput( attrs={ "placeholder": "First Name", "class": "form-control" } )) lastname = forms.CharField( widget=forms.TextInput( attrs={ "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/models.py file and add the following code:
core/models.pyfrom 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 Migrationspython manage.py makemigrations
After successfully run the above command go to the core/migrations/0001_initial.py
core/migrations/0001_initial.py# 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 = [ migrations.CreateModel( name='Employee', fields=[ ('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 manage.py migrateStep 7 : Creating the Views
In this step, we need to create the views for performing fetch record to the database.Open the core/views.py file and add:
core/views.pyfrom 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 = form.save() ser_instance = serializers.serialize('json', [ instance, ]) return JsonResponse({"instance": ser_instance}, status=200) else: # 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"> <head> <meta charset="UTF-8"> <title>Tuts-Station.com</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> </head> <body> <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 - Tuts-Station.com</h3> </div> <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> </div> <form> </div> </div> </div> </div> <br> <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> <div class="card-body"> <table class="table table-striped table-sm" id="my_friends"> <thead> <tr> <th>First name</th> <th>Last name</th> </tr> </thead> <tbody> {% for employee in employees %} <tr> <td>{{employee.firstname}}</td> <td>{{employee.lastname}}</td> </tr> {% endfor %} </tbody> </table> </div> </div> </div> </div> </div> </body> <script> /*------------------------------------------ -------------------------------------------- About -------------------------------------------- --------------------------------------------*/ $("#form-submit").submit(function (e) { e.preventDefault(); var serializedData = $(this).serialize(); $.ajax({ type: 'POST', url: "{% url 'post_store' %}", data: serializedData, success: function (response) { $("#form-submit").trigger('reset'); var instance = JSON.parse(response["instance"]); var fields = instance[0]["fields"]; $("#my_friends tbody").prepend( `<tr> <td>${fields["firstname"]||""}</td> <td>${fields["lastname"]||""}</td> </tr>` ) }, error: function (response) { alert(response["responseJSON"]["error"]); } }) }) </script> </html>Step 9 : Creating URLs
In this section, we’ll create the urls to access our CRUD views.Go to the urls.py core/urls.py file and update it as follows:
core/urls.pyfrom 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 urls.py your root preoject folder lets update the file.
example/urls.pyfrom django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), 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 manage.py runserver
Next, go to the http://localhost:8000/cores address with a web browser.
I Hope It will help you....