Django Ajax Form Validation Example

Published On: 03/08/2022 | Category: Django

Hi Dev,

Now, let's see article of django ajax form validation. I explained simply step by step django ajax form validation example. this example will help you submitting a form with ajax django. This post will give you simple example of django submit form without refresh.

Now, you can submit the form using jquery and without the page refresh. When we submit an ajax form in django, we will add csrf token in ajax request.

In this article i will share you how to utilize django default validation with jquery ajax. Here we also print django validation message when false. So if you want to ajax form validation in django app then you are right place.

You can use these examples with django3 (django 3) version.

Here,you can just follow bellow all step to create ajax validation 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

Here, do not forget to register the new app in the file. Under installed apps, just add ‘core’ to the list:


Step 4: Create a Model

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

from django.db import models

# Create your models here.
class Contact(models.Model):  
    name = models.CharField(max_length=100)
    email = models.EmailField()
    contact = models.CharField(max_length=100)

Step 5 : Create a Form

In this step We need to create a form that will be used in our image upload add a bootstrap class and validation etc.. plus we need to add custom styling.

from django import forms
from .models import Contact

class ContactForm(forms.ModelForm):

    name = forms.CharField(max_length=100,
                               widget=forms.TextInput(attrs={'placeholder': 'Name',
                                                             'class': 'form-control',
                                                             }),error_messages={'required':'The name field is required.'})
    email = forms.EmailField(required=True,
                             widget=forms.TextInput(attrs={'placeholder': 'Email',
                                                           'class': 'form-control',
                                                           }),error_messages={'required':'The email field is required.'})

    contact = forms.CharField(required=True,
                             widget=forms.TextInput(attrs={'placeholder': 'Contact',
                                                           'class': 'form-control',
                                                           }),error_messages={'required':'The contact field is required.'})
    class Meta:  
        model = Contact  
        fields = "__all__"
Step 6 : Creating the Views

In this step, we need to create the views for performing ajax image upload to the database.Open the core/ file and add.

# Create your views here.
from django.shortcuts import render
from django.http import JsonResponse
from .forms import ContactForm

# Create your views here.
def contactForm(request):
    if request.is_ajax() and request.method == 'POST':
       form = ContactForm(request.POST)
       if form.is_valid():
           return JsonResponse({'success': True, 'message': 'Form Saved Successfully!'})
           return JsonResponse({'error': True, 'error': form.errors})
        form = ContactForm()
        return render(request, 'index.html', {'form': form})
Step 7 : Creating the Templates

So, finally we are here to this step we need to creating django templates following below file:

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

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <title>Django Ajax Form Validation Example</title>
    <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">
                        <h4>Django Ajax Form Validation Example - <span class="text-primary"></span></h4>
                    <div class="card-body">

                        <div class="alert alert-danger error-msg" style="display:none">

                        <form novalidate>
                            {% csrf_token %}
                            <div class="form-row">
                                <div class="col-md-12">
                                    <div class="form-group">
                                        <label class="small mb-1">Name:</label>
                                        {{ }}
                            <div class="form-row">
                                <div class="col-md-12">
                                    <div class="form-group">
                                        <label class="small mb-1">Email:</label>
                                        {{ }}
                            <div class="form-row">
                                <div class="col-md-12">
                                    <div class="form-group">
                                        <label class="small mb-1">Contact:</label>
                                        {{ }}
                            <div class="form-group mt-2 mb-0">
                                <button type="submit" class="btn btn-success btn-submit">Submit</button>
<script type="text/javascript">

    Validation Logic 
    $(document).ready(function() {
            var name = $("input[name='name']").val();
            var email = $("input[name='email']").val();
            var contact = $("input[name='contact']").val();
                url:"{% url 'contactForm' %}",
                dataType: 'json',
                    'csrfmiddlewaretoken': $("input[name=csrfmiddlewaretoken]").val(),
                success:function (data) {
                    if ($.isEmptyObject(data.error)) {

        Print Error Msg 
        function printErrorMsg(msg) {
            $.each( msg, function( key, value ) {

Step 8 : Creating URLs

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

from django.urls import path
from . import views

urlpatterns = [
    path('form/', views.contactForm, name="contactForm"),

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('blog.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 address with a web browser.


I Hope It will help you....