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 settings.py file.
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR,'smo_temp')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]
signup_student.html
{% extends 'temp_basic.html' %}

{% block content %}
{{msg}}
<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>
</form>
{% endblock %}
temp_basic.html
<html>
<head>
<title>This is basic template file </title>
</head>
<body>
{% block content %}

{% endblock %}
<br><br>
<center>Displayed by using template file temp_basic.html</center>
</body>
</html>
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 urls.py file to add the path to our form.

urls.py
from django.urls import path 
from  . import views

# Create your views here.
urlpatterns=[
    path('',views.index,name='index'),
    path('student/signup_student',views.signup_student,name='signup_student'),
    path('student/signup_student_output',views.signup_student_output,name='signup_student_output2')
]

Creating table

In the Django framework we need not create our table by using SQL queries so we will write our model.

model.py
from django.db import models
# Create your models here.
class student(models.Model):
    name =models.CharField(max_length=100)
    cl=models.CharField(max_length=10,db_column='class')
    mark =models.IntegerField()
    gender  =models.CharField(max_length=6)
    class Meta:
        db_table='student'
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:
        db_table='student'

Database details ( MySQL )

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

Migrations

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 manage.py makemigrations
You need to apply this.
python manage.py 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 http://127.0.0.1:8000/my_app/student/signup_student in browser ( server is running ) , our urls.py 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 urls.py page.
path('student/signup_student',views.signup_student,name='signup_student')
Here signup_student() is declared inside views.py 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 urls.py ( check above for code of urls.py ) we have this line.
path('student/signup_student_output',views.signup_student_output,name='signup_student_output2')
Here signup_student_output() is declared inside views.py ( check the code for views.py below ).
We used the student model ( check models.py 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.

views.py
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):
    en=student(name=request.POST.get('name'),cl=request.POST.get('class'),
     mark=request.POST.get('mark'),gender=request.POST.get('gender'))
    en.save()
    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):
    en=student(name=request.POST.get('name'),cl=request.POST.get('class'),
     mark=request.POST.get('mark'),gender=request.POST.get('gender'))
    en.save()
    str1="Data inserted to student table with id:" + str(en.id) 
    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


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com



    22-01-2023

    Hi,
    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 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer