Python - Django Simple Submit Form With Ajax
Submitted by razormist on Sunday, October 1, 2017 - 18:02.
In this tutorial we will create a Simple Submit Form With Ajax. Django is a open source web application framework and it is a set of components that helps you to develop websites faster and easier. By using Django the components are already built you just need to modify and assign them for your need. So let's now do the coding...
It will be look like this:
Then after that create a view that will catch the redirect url. To do that create a file "views.py" then copy/paste the code below and save it as "views.py".
After the Models are created go to "admin.py", then copy and paste the code below
This block of code will display the details of data in the database called "Member".
Save it as "base.html" inside the ajax directory "sub directory of templates".
index.html
Save it as "index.html" inside the ajax directory "sub directory of templates".
Getting Started
First you will have to download & install the Python IDLE's, here's the link for the Integrated Development And Learning Environment for Python https://www.python.org/downloads/. After Python IDLE's is installed, open the command prompt then type "pip install Django", and hit enter. Wait for the django to be downloaded and installed at the same time. Then After that type "python -m django version" and hit enter to check if django is installed and what version of django is.Creating the App
After django is set we will now create the web app. While your in the command prompt cd to the directory you want to save the app, then type "django-admin startproject server" and hit enter. A new folder will be created on the directory named 'server'.Running The Server
After creating the project, cd to the newly created directory, then type "manage.py runserver" and hit enter to start the server running. The "manage.py" is a command of django-admin that utilize the administrative tasks of python web framework. Here is the image of python web server: Note: Type '127.0.0.1:8000' in the url browser to view the server. When there is code changes in the server just (ctrl + C) to command prompt to stop the server from running, then start again to avoid errors.Creating The Website
This time will now create the web app to display the web models. First locate the directory of the app via command prompt cd, then type "manage.py startapp ajax" and hit enter. A new directory will be created named "ajax".Setting up The URL
This time will now create a url address to connect the app from the server. First Go to server directory, then open urls via Python IDLE's or any text editor. Then import "include" module beside the url module and import additional module to make a redirect url to your site "from . import views". After that copy/paste the code below inside the urlpatterns.- url(r'^$', views.index_redirect, name="index_redirect"),
- url(r'^ajax/', include("ajax.urls")),
- from django.conf.urls import url, include
- from django.contrib import admin
- from . import views
- urlpatterns = [
- url(r'^$', views.index_redirect, name="index_redirect"),
- url(r'^ajax/', include("ajax.urls")),
- url(r'^admin/', admin.site.urls),
- ]
- from django.shortcuts import redirect
- def index_redirect(request):
- return redirect('/ajax/')
Creating The Path For The Pages
Now that we are all set we will now create a path for the web pages. All you have to do first is to go to ajax directory, then copy/paste the code below and save it inside "ajax" directory named 'urls.py' The file name must be urls.py or else there will be an error in the code.- from django.conf.urls import url
- from . import views
- urlpatterns = [
- url(r'^$', views.index, name="index"),
- url(r'^insert$', views.insert, name="insert")
- ]
Creating A Static Folder
This time we will create a directory that store an external file. First go to the ajax directory then create a directory called "static", after that create a sub directory called "ajax". You'll notice that it is the same as your main app directory name, to assure the absolute link. This is where you import the css, js, etc directory. To get the jQuery framework download it here https://jquery.com/ For the bootstrap framework you get it from here http://getbootstrap.com/Creating The Views
The views contains the interface of the website. This is where you assign the html code for rendering it to django framework and contains a methods that call a specific functions. To do that first open the views.py, the copy/paste the code below.- from django.shortcuts import render, redirect
- from .models import Member
- # Create your views here.
- def index(request):
- return render(request, 'ajax/index.html')
- def insert(request):
- member = Member(firstname=request.POST['firstname'], lastname=request.POST['lastname'], age=request.POST['age'], address=request.POST['address'])
- member.save()
- return redirect('/')
Creating The Models
Now that we're done with the views we will then create a models. Models is module that will store the database information to django. To do that locate and go to ajax directory, then open the "models.py" after that copy/paste the code.- from django.db import models
- # Create your models here.
- class Member(models.Model):
- firstname = models.CharField(max_length=40)
- lastname = models.CharField(max_length=40)
- age = models.CharField(max_length=40)
- address = models.CharField(max_length=40)
- def __str__(self):
- return self.firstname + " " + self.lastname
- from django.contrib import admin
- from .models import Member
- # Register your models here.
- admin.site.register(Member)
Registering The App To The Server
Now that we created the interface we will now then register the app to the server. To do that go to the web directory, then open "settings.py" via Python IDLE's or any text editor. Then copy/paste this script inside the INSTALLED_APP variables 'web'. It will be like this:- INSTALLED_APPS = [
- 'ajax',
- 'django.contrib.admin',
- 'django.contrib.auth',
- 'django.contrib.contenttypes',
- 'django.contrib.sessions',
- 'django.contrib.messages',
- 'django.contrib.staticfiles',
- ]
Creating The Mark up Language
Now we will create the html interface for the django framework. First go to ajax directory, then create a directory called "templates" and create a sub directory on it called ajax. base.html- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1">
- {% load static %}
- <link rel="stylesheet" type="text/css" href="{% static 'ajax/css/bootstrap.css' %}"/>
- </head>
- <body>
- <nav class="navbar navbar-default">
- <div class="container-fluid">
- </div>
- </nav>
- <div class="col-md-6 well">
- <hr style="border-top:1px dotted #000;"/>
- {% block body %}
- {% endblock %}
- </div>
- </body>
- </html>
- {% extends 'ajax/base.html' %}
- {% block body %}
- <form method="POST">
- {% csrf_token %}
- <div class="form-group">
- <input type="text" class="form-control" id="firstname"/>
- </div>
- <div class="form-group">
- <input type="text" class="form-control" id="lastname"/>
- </div>
- <div class="form-group">
- <input type="text" class="form-control" id="age"/>
- </div>
- <div class="form-group">
- <input type="text" class="form-control" id="address" />
- </div>
- <br />
- <div class="form-group">
- </div>
- </form>
- {% endblock %}
Creating The Ajax Script
Now then we will create the ajax script that we will be implementing in Django. First thing to do is simply go to ajax directory then go to 'static/ajax' select "js" and create a file called "script.js", and after that copy/paste the code below.- $(document).ready(function(){
- $('#btn_submit').on('click', function(){
- $firstname = $('#firstname').val();
- $lastname = $('#lastname').val();
- $age = $('#age').val();
- $address = $('#address').val();
- if($('#firstname').val() == "" || $('#lastname').val() == "" || $('#age').val() == "" || $('#address').val() == ""){
- alert("Please fill up the required field");
- }else{
- $.ajax({
- type: "POST",
- url : "insert",
- data: {
- firstname: $firstname,
- lastname: $lastname,
- age: $age,
- address: $address,
- csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
- },
- success: function(){
- alert("Saved Data!");
- $('#firstname').val('');
- $('#lastname').val('');
- $('#age').val('');
- $('#address').val('');
- }
- });
- }
- });
- });
Migrating The App To The Server
Now that we done in setting up all the necessary needed, we will now then make a migration and migrate the app to the server at the same time. To do that open the command prompt then cd to the "server" directory, then type "manage.py makemigrations" and hit enter. After that type again "manage.py migrate" then hit enter. Now try to run the server again, and see if all things are done. There you have it we successfully created a Simple Submit Form With Ajax. I hope that this simple tutorial help you for what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!!!Add new comment
- 415 views