Django Form submission without Page Reload


In Django, we can submit the form without reloading the page using the Jquery and Ajax (Asynchronous JavaScript and XML) requests.

Let’s see an example to work with the Ajax to submit the Django form without reloading the page.

Create a new Django project

First create a new project in Django with the name Reload_project and also create a new app in the project directory with the name Reloadapp by executing the below commands in the command prompt.

django-admin startproject Reload_project
cd Reload_project
django-admin startapp Reloadapp

Now in INCLUDED_APPS in settings.py file of the Reload_project directory, add the new app name.

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "Reloadapp",
]

Next in models.py file add the code which resembles to define the datatype, size etc of the fields defined in the html form.

from django.db import models
# Create your models here.
class Todo(models.Model):
	task = models.CharField(max_length=200)
	def __str__(self):
		return f"{self.task}"

After this, we need to register the model with the admin.py file, which is located in the Reload_project directory.

from django.contrib import admin
from .models import *
# Register your models here.
admin.site.register(Todo)

Now create the templates folder in the Reload_app and in that folder create a html file with the form to be displayed on the webpage.

<!DOCTYPE html>
<html>
<head>
   <title>Todo List</title>
</head>
<body>
   <form method="post" id="task-form">
      {% csrf_token %}
      <input type="text" placeholder="Enter Task" name="task" id="task" required>
	  <button type="submit">Save</button>
   </form>
   <script src="https://code.jquery.com/jquery-3.5.1.js"
      integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc="
         crossorigin="anonymous"></script>
   <script type="text/javascript">
   $(document).on('submit','#task-form',function(e){
      e.preventDefault();
	  $.ajax({
	     type:'POST',
		 url:'{% url "home" %}',
		 data:
		 {
            task:$("#task").val(),
			csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
		 },
		 success:function(){
			alert('Saved');
			   }
		 })
	  });
   </script>
</body>
</html>

Later create the code in the views.py file to handle the post and request handling as per the user requirement.

from django.shortcuts import render
from .models import Todo
# Create your views here.
def home(request):
	if request.method == 'POST':
		task=request.POST.get('task')
		print(task)
		new = Todo(task=task)
		new.save()
	return render(request,"main/form.html")

After creating the views.py file, we have to add the urls of the html forms created in the urls.py file of the Reload_app.

from django.urls import path
from .views import *
urlpatterns = [
	path('',home,name="home"),
]

Now we have to add all the urls path of the app to the urls.py file in the Reload_project.

from django.contrib import admin
from django.urls import path,include
urlpatterns = [
   path("admin/", admin.site.urls),
   path("",include("Reload_app.urls"))
]

Finally do the migrations of the data and run the server to visit the create website.

python manage.py makemigrations
python manage.py migrate
python manage.py runserver

The website will look like this and when we save the task the page will not be reloaded.

Updated on: 06-Nov-2023

199 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements