Django Form Submit using Form.js Example

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


Hi Dev,

Now, let's see article of django form submit using form.js example. I explained simply step by step django jquery form-js example. I would like to share with you how to without page refresh form submit using form js plugin. I would like to show you how to submit form using jquery in django.

Immediately submits the form through AJAX. In the most common use case this is invoked in response to the user clicking a submit button on the form. Use ajaxSubmit if you want to bind your own submit handler to the form.

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

let's see below simple example with output:

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 manage.py startapp core
Step 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 : Database Setup

Next step, we will modify the settings.py file and update the database settings to configure the mydb database:

settings.py
DATABASES = {  
    'default': {  
        'ENGINE': 'django.db.backends.mysql',  
        'NAME': 'example',  
        'USER':'root',  
        'PASSWORD':'root',  
        'HOST':'localhost',  
        'PORT':'3306'  
    }  
}  
Step 5: 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
from django.contrib.auth.models import User

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

    def __str__(self):
        return self.name

Step 6 : 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 Student

class StudentForm(forms.ModelForm):
    name = forms.CharField(
        widget=forms.TextInput(
            attrs={
                "placeholder": "Name",
                "class": "form-control",
                "id": "name"
            }
        ))
    email = forms.EmailField(
        widget=forms.EmailInput(
            attrs={
                "placeholder": "Email",
                "class": "form-control",
                "id": "email"
            }
        ))

    class Meta:
        model = Student
        fields = ("__all__")
Step 7 : 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
from django.shortcuts import render
from django.http import JsonResponse
from .forms import StudentForm

# Create your views here.
def contact_form(request):
    if request.is_ajax() and request.method == 'POST':
       form = StudentForm(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 = StudentForm()
        return render(request, 'index.html', {'form': form})
Step 8 : 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">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Django Form Submit using Form.js Example - Tuts-Station.com</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.form/4.3.0/jquery.form.min.js"></script>
</head>
<body>
    <div class="container mt-5 pt-5">
        <div class="row">
            <div class="col-md-6 mx-auto">
                <div class="card">
                    <div class="card-header">
                        <h5>Django Form Submit using Form.js Example - <span class="text-primary">Tuts-Station.com</span></h5>
                    </div>
                    <div class="card-body">
                        <div class="alert alert-success success-msg" style="display:none"></div>
                        <div class="alert alert-danger error-msg" style="display:none">
                            <ul></ul>
                        </div>
                        <form action="{% url 'contactForm' %}" method="POST">
                            {% csrf_token %}
                            <div class="row">
                                <div class="col-md-12">
                                    <div class="form-group">
                                        <label for="name">Name:</label>
                                        {{ form.name }}
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-12">
                                    <div class="form-group">
                                        <label for="email">Email:</label>
                                        {{ form.email }}
                                    </div>
                                </div>
                            </div>
                            <button class="btn btn-success savebtn" type="submit">Submit</button>
                            <button class="btn btn-secondary resetbtn" type="reset">Reset</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>

<script type="text/javascript">
    $(document).ready(function(){

        /*------------------------------------------
        --------------------------------------------
        About 
        --------------------------------------------
        --------------------------------------------*/
        var options = { 
                complete: function(response) 
                {    
                    if($.isEmptyObject(response.responseJSON.error)){
                        $('.success-msg').css('display','block');
                        $('.success-msg').text(response.responseJSON.message);
                        $('#name').val('');
                        $('#email').val('');
                    }else{
                        printErrorMsg(response.responseJSON.error);
                    }
                },
                error:function(response){
                    console.log(response);
                }
            };

        $('.savebtn').click(function(e) {
            e.preventDefault(); 
            $(this).parents("form").ajaxSubmit(options);
        });

        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>
</html>
Step 9 : 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.py
from django.urls import path
from . import views

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

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

example/urls.py
from 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 address with a web browser.

http://localhost:8000/form/

I Hope It will help you....