Django: Inserting Form data to MySQL table

Django MySQL Database Display Records

Displaying Form to take user input

We will create one web form to take input from users. This page we will keep inside our template directory as smo_temp/signup_student.html. To setup the template directory you can change the file.
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR,'smo_temp')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
{% extends 'temp_basic.html' %}

{% block content %}
<form  action='signup_student_output' method=POST>
    {% csrf_token %}
name :<input type=text name=name><br>
class :<input type=text name=class><br>
Mark :<input type=text name=mark><br>
Gender :<input type=text name=gender><br>
<input type=submit value=Submit>
{% endblock %}
<title>This is basic template file </title>
{% block content %}

{% endblock %}
<center>Displayed by using template file temp_basic.html</center>
Here four inputs are taken from user. To keep it simple we are not validating any input data here and expecting integer to be entered by user in mark field.

Adding URL

Inside our apps directory we will use the file to add the path to our form.
from django.urls import path 
from  . import views

# Create your views here.

Creating table

In the Django framework we need not create our table by using SQL queries so we will write our model.
from django.db import models
# Create your models here.
class student(models.Model):
    name =models.CharField(max_length=100)
    mark =models.IntegerField()
    gender  =models.CharField(max_length=6)
    class Meta:
Here watch the way we used one column name class, because class is a reserved keyword in Python.

Watch the class Meta, here we are saying that the table name is student. If we don't use Meta then the name of the table will be <app_name>_student.
class Meta:

Database details ( MySQL )

Inside our keep login details like this.
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'database_name',
		'USER' : 'userid_here',
		'PASSWORD' :'password_here',
		'HOST' : 'localhost'


We have to create migrations based on inputs we have in our Model. This is required for the first time to create the table and when we do any changes at Database side, Django keeps the history of changes. Wath the file created inside your migrations folder.
At command prompt enter this.
python makemigrations
You need to apply this.
python migrate
You will get output like this .
makemigrations and migrate at command prompt
Once the migration is applied, Django will create some tables inside our MySQL database including our required table student.

Creating views

When user enters the url in browser ( server is running ) , our page will send the request to our signup_student.html page by using the view signup_student(). This happens due to the entry ( check above ) inside page.
Here signup_student() is declared inside file ( check the code below. With this we display the html form inside our signup_student.html file.

form to enter data

Once the user enters the data and submits the form, the action attribute of the form request for signup_student_output
<form  action='signup_student_output' method=POST>
Inside our ( check above for code of ) we have this line.
Here signup_student_output() is declared inside ( check the code for below ).
We used the student model ( check above ) to insert the data we collect from the form to our table.
The variables of the form is collected like this ( highlighted below ) and assigned to columns of the student table. Here name,cl,mark,gender are connecting to respective columns of our table.
from django.shortcuts import render
from django.http import HttpResponse
from .models import student
# Create your views here.
def index(request):
    return render(request,'form.html')

def signup_student(request):
    return render(request,'signup_student.html',{'msg':'Student Signup'})
def signup_student_output(request):
    str1="Data inserted to student table" 
    return render(request,'signup_student.html',{'msg':str1})

Getting the unique id of inserted row

While creating the table Django has added one AUTO_INCREMENT column id. One unique id is added to the row by mysql when we insert any record to the table. This id we can collect after saving the record in our table. Here is the code changes we have done to collect the unique id. Here we used str() to convert the id value to string while adding to the string variable str1.
def signup_student_output(request):
    str1="Data inserted to student table with id:" + str( 
    return render(request,'signup_student.html',{'msg':str1})
Watch the id displayed after adding the record to our student table.
autoincrement id of the inserted row
Data display Adding multiple records to MySQL table
Subscribe to our YouTube Channel here


* indicates required
Subscribe to plus2net


    I've wll executed all what you taught in your tutorial, I am having some errors that tell me my db_table = 'user' name is not defined. What to do ?

    Post your comments , suggestion , error , requirements etc here

    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 All rights reserved worldwide Privacy Policy Disclaimer