Django Insert record with Ajax

run the following command - This will create a my_project  directory in your current directory

D:\>django-admin startproject  djangoajax

then go to myproject folder path type following command :-


D:\>cd  djangoajax


To create your app, make sure you’re in the your project  directory &  type this command:


D:\djangoajax>python manage.py  startapp hello 

That’ll create a directory hello app folder inside djangoajax folder:-

after it open your   D: drive  inside it you will see  djangoajax folder 





When you will open your hello folder you will see:-








(1)models.y file code :-


from django.db import models

# Create your models here.

class ContactForm(models.Model):
       

    fullname= models.CharField(max_length=100)
    email= models.EmailField()
    contact= models.CharField(max_length=50)
    message= models.CharField(max_length=200)


After creating this model, we need to run two commands in order to create Database for the same.

Python manage.py makemigrations
Python manage.py migrate

forms.py file code:-


from django import forms
from .models import ContactForm


class FormContactForm(forms.ModelForm):
    class Meta:
        model= ContactForm
        fields= ["fullname", "email", "contact", "message"]
        widgets={'fullname':forms.TextInput(
              attrs={'class':'form-control','id':'fullname'}),
                 'email':forms.TextInput(
                       attrs={'class':'form-control','id':'email'}),
                 'contact':forms.TextInput(
                       attrs={'class':'form-control','id':'contact'}),
                 'message':forms.Textarea(
                       attrs={'class':'form-control','id':'message'})
                 
}


2) admin.py file code:-


from django.contrib import admin
from .models import *

# Register your models here.

admin.site.register(ContactForm)



3)views.py file code:- 

from django.shortcuts import render
from  hello.forms import FormContactForm
from .models import *
from django.http import JsonResponse

# Create your views here.
def showform(request):
    form= FormContactForm(request.POST or None)
   
 
    context= {'form': form }
       
    return render(request, 'contactform.html', context)

def saveform(request):
   
    form= FormContactForm(request.POST or None)
    if form.is_valid():
        fn=request.POST['fullname']
        em=request.POST['email']
        cn=request.POST['contact']
        msg=request.POST['message']
        data=ContactForm(fullname=fn,email=em,contact=cn,message=msg)
        result=data.save()
        return JsonResponse({'status':'Save'})

   
       
              
def index(request):
    return render(request, 'index.html')

4) urls.py file code of your app folder :-

from django.urls import path

from .import views



urlpatterns=[
path('',views.index,name='index'),


path('showform/', views.showform,name='showform'),
path('showform/saveform/', views.saveform,name='saveform'),


]


5)create templates folder inside your app folder and create html files 


contactform.html file :-

<!DOCTYPE html>  
<html lang="en">  
<head>
    {% load static %}
 
<meta charset="UTF-8">  
<title>Django Contact Form</title>  
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"
crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>
<script
src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"
integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
crossorigin="anonymous"></script>
<script src="{% static 'js/script.js' %}"></script>
</head>  
<body>  
    <div class="container">
<form>  
{% csrf_token %}  
{{ form.as_p }}
<div class="form-group">
<button type="button" id="btnsave" class="btn btn-primary">Submit</button>
</div>
</div>
</form>  


</body>  
</html>


index.html file code:-

<h1> welcome page </h1>


6)create static folder inside your app folder  and create js folder inside your static folder and inside js 

folder create  script.js file :-


$(document).ready(function(){

$("#btnsave").click(function()
{
    let fullname = $('#fullname').val();
    let  email = $('#email').val();
    let  contact = $('#contact').val();
    let  message = $('#message').val();
    let csr=$('input[name=csrfmiddlewaretoken]').val()

mydata={fullname:fullname,email:email,contact:contact,message:message,
csrfmiddlewaretoken:csr};

$.ajax({

    url: 'saveform/',
    type: 'POST',
    data: mydata,
    success:function(data){
        if(data.status=='Save')
    {
        console.log(data);
       
        alert("New Member Successfully Added");
    }
    else{
        alert("Not Added");
    }

    }

    });

});

});


7)run project  and see output as shown bleow





8) after submission you will see  alert message record added successfully. as shown below:-




Previous
Next Post »