Open In App

Django Form submission without Page Reload

Last Updated : 16 Feb, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. Built by experienced developers, it takes care of much of the hassle of Web development, so you can focus on writing your app without needing to reinvent the wheel. It’s free and open source.

In this article we will see form submission in django without reloading the page using Jquery and Ajax

For installing django open cmd or terminal and write below command

pip3 install django

Then create new project

django-admin startproject newproj
cd newproj

Then for creating new app 

Windows

python manage.py startapp main

Ubuntu

python3 manage.py startapp main

Add your app name in settings.py

Create new directory inside app and name it as templates inside that create another directory and name it as main(Your app name)

Run this command to migrate

python manage.py migrate

Create new model inside models.py

models.py

Python3




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}"


python manage.py makemigrations
python manage.py migrate

admin.py

Python3




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


Create new file inside templates directory and name it as form.html

HTML




<!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>
  
          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>


Create new view inside views.py to handle get and post  request.

Python3




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")


Create new file inside your app and name it as urls.py

Python3




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


Add main.urls in project urls

myproj/urls.py

Python3




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


To run the app write command

python manage.py runserver

Output

Admin Page



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads