Django Ajax Form Validation Example

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 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
Here, do not forget to register the new app in the settings.py file. Under installed apps, just add ‘core’ to the list:
.... 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 Model
In this step we will require the database model for storing contacts.Open the core/models.py 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 form.like 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, required=True, 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/views.py file and add.
core/views.py# 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(): # form.save() return JsonResponse({'success': True, 'message': 'Form Saved Successfully!'}) else: return JsonResponse({'error': True, 'error': form.errors}) else: 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:
core/templates/index.html<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Django Ajax Form Validation Example</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"> <h4>Django Ajax Form Validation Example - <span class="text-primary">Tuts-Station.com</span></h4> </div> <div class="card-body"> <div class="alert alert-danger error-msg" style="display:none"> <ul></ul> </div> <form novalidate> {% csrf_token %} <div class="form-row"> <div class="col-md-12"> <div class="form-group"> <label class="small mb-1">Name:</label> {{ form.name }} </div> </div> </div> <div class="form-row"> <div class="col-md-12"> <div class="form-group"> <label class="small mb-1">Email:</label> {{ form.email }} </div> </div> </div> <div class="form-row"> <div class="col-md-12"> <div class="form-group"> <label class="small mb-1">Contact:</label> {{ form.contact }} </div> </div> </div> <div class="form-group mt-2 mb-0"> <button type="submit" class="btn btn-success btn-submit">Submit</button> </div> </form> </div> </div> </div> </div> </div> </body> <script type="text/javascript"> /*------------------------------------------ -------------------------------------------- Validation Logic -------------------------------------------- --------------------------------------------*/ $(document).ready(function() { $('body').on('click','.btn-submit',function(e){ e.preventDefault(); var name = $("input[name='name']").val(); var email = $("input[name='email']").val(); var contact = $("input[name='contact']").val(); $.ajax({ type:'POST', url:"{% url 'contactForm' %}", dataType: 'json', data:{ 'csrfmiddlewaretoken': $("input[name=csrfmiddlewaretoken]").val(), name:name, email:email, contact:contact, }, success:function (data) { if ($.isEmptyObject(data.error)) { $("input[name='name']").val(''); $("input[name='email']").val(''); $("input[name='contact']").val(''); }else{ printErrorMsg(data.error) } } }); }); /*------------------------------------------ -------------------------------------------- Print Error Msg -------------------------------------------- --------------------------------------------*/ function printErrorMsg(msg) { $('.error-msg').find('ul').html(''); $('.error-msg').css('display','block'); $.each( msg, function( key, value ) { $(".error-msg").find("ul").append('<li>'+value+'</li>'); }); } }); </script> </body> </html>Step 8 : Creating URLs
In this section, we’ll create the urls to access our views.Go to the urls.py core/urls.py file and update it as follows:
core/urls.pyfrom django.urls import path from . import views urlpatterns = [ path('form/', views.contactForm, name="contactForm"), ]
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('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 manage.py runserver
Next, go to the address with a web browser.
http://localhost:8000/form/
I Hope It will help you....