A simple student management system based on Django Web framework (Python)

Posted by rodneykm on Sun, 03 Oct 2021 20:55:49 +0200

Web development of student management system

Python

Author: bug Maker - Xiao Liu

Background:

After learning and mastering a certain basis of Python, I preliminarily learned and understood Django's web development framework and the basic usage of MySQL database. Through Django's learning, I completed the web development practice of simple student management system, and recorded the process of learning Django and the problems encountered

Environmental preparation

Installing the python environment

Installed, ignored here

Install Django

pip install django

Verify Django version installed

import django
print("Django Version is",django.get_version())
# The output result is: Django version is 3.2.7

Build project

Create Django project

django-admin startproject project_name

Create app

django-admin startapp app_name

Terminal create app

python manage.py startapp app

Start the server and run the program

python manage.py runserver

Configure MySQL

Installing the python environment

pip install pymysql

Modify the setting.py file

Configure the created app into the setting.py file

INSTALLED_APPS = [
   'django.contrib.admin',
   'django.contrib.auth',
   'django.contrib.contenttypes',
   'django.contrib.sessions',
   'django.contrib.messages',
   'django.contrib.staticfiles',
   'app', #app name
]

Configure MySQL database information

#You need to modify your own database file
#Where host is your local address, port is the port where you install the database, and password is the password to log in to the database
DATABASES = {
   'default': {
       'ENGINE': 'django.db.backends.mysql',
       'NAME': 'demo',
       'USER': 'root',
       'PASSWORD': 'root',
       'HOST': '127.0.0.1',
       'POST': '3306'
  }
}

Configure init.py file

from pymysql import install_as_MySQLdb
install_as_MySQLdb()

Start MySQL service

net start mysql

Log in to MySQL database

mysql -uroot -p

Create database

create database database_name charset utf8

Create Model class Model

from django.db import models
​
# Create your models here.
​
# 1. Create a model class
# Create user class
class UserInfo(models.Model):
# 2. Define field attributes
   UserId = models.AutoField(primary_key=True)
   username = models.CharField(max_length=16, blank=False, verbose_name="user name")
   password = models.CharField(max_length=16, blank=False, verbose_name="password")
​
# Create student information class
class StuInfo(models.Model):
   id = models.AutoField(primary_key=True)
   stuname = models.CharField(max_length=16, verbose_name="Student name")
   stuphone = models.CharField(max_length=16, verbose_name="Student telephone")
   stuaddress = models.CharField(max_length=16, verbose_name="Student address")
   stucollege = models.CharField(max_length=16, verbose_name="Student Department")
   stumajor = models.CharField(max_length=16, verbose_name="Student major")


Perform data migration on the terminal (each operation of Models.py is equivalent to the operation of database tables, and data migration is required)

python manage.py makemigrations

python manage.py migrate

admin site creation

Configure the information of the admin background site. The registration models are userinfo and empinfo

from django.contrib import admin
from .models import UserInfo, StuInfo
# Register your models here.
class UserInfoAdmin(admin.ModelAdmin):
   list_display = ['UserId', 'username', 'password']
​
class EmpInfoAdmin(admin.ModelAdmin):
   list_display = ['id', 'stuname', 'stuphone', 'stuaddress', 'stucollege', 'stumajor']
​
admin.site.register(UserInfo, UserInfoAdmin)
admin.site.register(StuInfo, EmpInfoAdmin)

Create administrator user

python manage.py createsuperuser

home page

Configure routing

Primary routing

Add a route under the app

path('', include('app.urls')),

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

Create secondary route

Create a routing file urls.py under APP

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

Create template

Create a template file templates under APP to store HTML page templates

Create a new home.html file to display the information content of the home page

home.html

<!DOCTYPE html>
<html lang="en">
​
<head>
   <meta charset="UTF-8">
   <title>home page</title>
<style>
   button{
      color: brown;
       border: 0px;
       font-size: 40px;
       line-height: 100px;
       background-color: transparent
  }
​
   body{
       text-align: center;
       background-size: 100%
  }
</style>
</head>
​
<body background="/static/1.jpg">
   <a href="login">
   <button type="submit">Welcome to the student information management system</button>
   </a>
</body>
</html>

Configure static folders

Create a static folder. Create a static folder under the app to store static files, such as pictures and background pictures displayed on HTML pages. Configure it in setting.py as follows

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [
   os.path.join(BASE_DIR, 'static'),
]

Write view module

from django.shortcuts import render
​
# Create your views here.
​
def home(request):
   return render(request, "home.html")
​
def login(request):
   return render(request, "login.html")

Sign in

Improve the login module and realize the login function

Front end login

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <title>Sign in</title>
</head>
<body background="/static/1.jpg" style="background: 100%">
<div  style="text-align: center; margin-top: 150px">
<form action="home" method="post" class="form-signin">
  {% csrf_token %}
   <h1>&nbsp&nbsp&nbsp Ascend&nbsp&nbsp record</h1>
   <label>account number:</label>
   <input placeholder="🐕account number"><br><br>
   <label>password:</label>
   <input placeholder="🔑password"><br><br>
   <button type="submit">Sign in</button>
</form>
</div>
</body>
</html>

Improve the front-end code and modify the login page

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <title>Sign in</title>
   <style>
       input,button{
   width: 320px;
   height: 45px;
   margin: 0px 8px;
   border-radius: 10px; /*Rounded rectangle*/
   text-indent: 10px; /*The first line of the invisible font inside is indented*/
   margin: 10px auto;
}
       body{
   margin: 0px;
   padding: 0px;
   height: 180px;
   background-image: url(/static/1.jpg);   /*Background picture*/
   background-size:100% 100%;   /*Picture free scaling*/
}
   </style>
​
</head>
<body background="/static/1.jpg" style="background-size: cover">
<div  style="text-align: center; margin-top: 60px">
<form action="/login/" method="post" class="form-signin" >
  {% csrf_token %}
   <h1 style="color: white; font-size: 60px">Welcome to the system</h1><br><br><br>
   <label style="color: white; font-size: 20px">account number:&nbsp</label>
   <input name="username"  type="text" style="width: 150px;height: 25px" placeholder="🐕account number"required autofocus><br><br>
   <label style="color: white; font-size: 20px">password:&nbsp</label>
   <input name="password" type="password" style="width: 150px;height: 25px"  placeholder="🔑password"required><br><br>
   <div style="padding-left: 70px">
       <button type="reset"style="width: 70px;height: 30px;font-size: 15px;color: palevioletred" >Reset</button>&nbsp
       <button type="submit"style="width: 70px;height: 30px;font-size: 15px;color: palevioletred" >Sign in</button>
   </div>
   <p style="color: brown; padding-left: 70px">{{msg}}</p>
</form>
​
</div>
</body>
​
</html>

Back end part

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <title>welcome</title>
   <style>
       body{
           background: pink;
      }
       div{
           text-align: center;
           padding-top: 50px;
      }
       h1{
           font-size: 50px;
           color: blue;
           text-align: center;
           padding-top: 50px;
      }
       button {
           width: 300px;
           height: 45px;
           font-size: 20px;
           color: brown;/*Font color*/
           border-color: blue;/*Border color*/
           border-radius: 20px;/*Rounded rectangle*/
​
      }
​
   </style>
</head>
<body>
​
<h1>Welcome to the student management system</h1>
<div>
   <button type="submit">Add student information</button><br><br>
   <button type="submit">Delete student information</button><br><br>
   <button type="submit">Modify student information</button><br><br>
   <button type="submit">View student information</button><br><br>
   <a href="/login">
   <button type="button">Return to the login page</button>
   </a>
</div>
</body>
</html>

Realize the function of returning to the login page

use a Tagged href Jump link

<a href="/login">
<button type="button">Return to the login page</button>
</a>

 

 

main interface

After logging in, enter the main interface, namely the welcome interface

Create a welcome HTML template in the templates template

Front end part welcome

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <title>welcome</title>
   <style>
       body{
           background: pink;
      }
       div{
           text-align: center;
           padding-top: 50px;
      }
       h1{
           font-size: 50px;
           color: blue;
           text-align: center;
           padding-top: 50px;
      }
       button {
           width: 300px;
           height: 45px;
           font-size: 20px;
           color: brown;/*Font color*/
           border-color: blue;/*Border color*/
           border-radius: 20px;/*Rounded rectangle*/
​
      }
​
   </style>
</head>
<body>
​
<h1>Welcome to the student management system</h1>
<div>
   <button type="submit">Add student information</button><br><br>
   <button type="submit">Delete student information</button><br><br>
   <button type="submit">Modify student information</button><br><br>
   <button type="submit">View student information</button><br><br>
   <a href="/login">
   <button type="button">Return to the login page</button>
   </a>
</div>
</body>
</html>

Realize the function of returning to the login page

use a Tagged href Jump link

<a href="/login">
<button type="button">Return to the login page</button>
</a>

Realize the function of adding student information

Front end part

Create an add.html template

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <title>Add information</title>
<style>
   body{
       background: lightblue;
       text-align: center;
  }
   h1{
       font-size: 30px;
       padding-top: 30px;
  }
   label,input{
       font-size: 20px;
      /* border-top: 20px;             padding-top: 20px;padding */
       margin-top: 15px;/*Margin */
       width: 180px;   /*Input box length*/
  }
   button{         /*Control button position, size and spacing*/
       font-size: 25px;
       margin-left: 60px;
       margin-right: -20px;
       /*border-radius: 10px;*/
       color: deepskyblue;
  }
​
</style>
</head>
<body>
<h1>Please fill in the basic information of students in the following information column</h1><br>
<div>
<form id="StuInfo" action="/add/" method="post">
  {% csrf_token %}
   <label>Student number:</label>
   <input type="text"name="id"required autofocus><br>
   <label>Student name:</label>
   <input type="text"name="stuname"required autofocus><br>
   <label>Student telephone:</label>
   <input type="text"name="stuphone"required autofocus><br>
   <label>Student address:</label>
   <input type="text"name="stuaddress"required autofocus><br>
   <label>Student Department:</label>
   <input type="text"name="stucollege"required autofocus><br>
   <label>Student major:</label>
   <input type="text"name="stumajor"required autofocus><br>
​
</form>
<p style="font-size: 20px; color: red; padding-left: 60px">
      {% if err %}
          {{ err }}
      {% endif %}
</p>
<p style="padding-left: 90px;font-size: 20px">
      {% if success %}
          {{ success }}
      {% endif %}
</p>
</div>
<div>
​
   </p>
   <button type="reset" form="StuInfo">empty</button>
   <button type="submit" form="StuInfo">Submit</button><br><br>
   <a href="/welcome">
       <button style="width: 180px">Return to main page</button>
   </a>
   </div>
</body>
</html>

Back end part (views view)

def add(request):
   if request.method == 'GET':
       return render(request, 'add.html')
   elif request.method =='POST':
       list = ['id', 'stuname', 'stuphone', 'stuaddress', 'stucollege', 'stumajor']
       info = []
       for li in list:
           info.append(request.POST.get(li))
       if globals()['LoginId'] != 1:
           return HttpResponse("wrong root User, do not have permission to add user!")
       s = models.StuInfo.objects.filter(id=info[0])
       if s.count != 0:
           return render(request, 'add.html', {'err': 'Student information already exists, please do not add it again'})
       stu = models.StuInfo()
       stu.id = info[0]
       stu.stuname = info[1]
       stu.stuphone = info[2]
       stu.stuaddress = info[3]
       stu.stucollege = info[4]
       stu.stumajor = info[5]
       stu.save()  #Save data
       return render(request, 'add.html', {'success': 'Student information added successfully!!'})def add(request):
   if request.method == 'GET':
       return render(request, 'add.html')
   elif request.method =='POST':
       list = ['id', 'stuname', 'stuphone', 'stuaddress', 'stucollege', 'stumajor']
       info = []
       for li in list:
           info.append(request.POST.get(li))
       if globals()['LoginId'] != 1:
           return HttpResponse("wrong root User, do not have permission to add user!")
       s = models.StuInfo.objects.filter(id=info[0])
       if s.count != 0:
           return render(request, 'add.html', {'err': 'Student information already exists, please do not add it again'})
       stu = models.StuInfo()
       stu.id = info[0]
       stu.stuname = info[1]
       stu.stuphone = info[2]
       stu.stuaddress = info[3]
       stu.stucollege = info[4]
       stu.stumajor = info[5]
       stu.save()  #Save data
       return render(request, 'add.html', {'success': 'Student information added successfully!!'})


   

Realize the function of deleting student information

Front end part

Create a template delete.html and add a route map

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <title>Delete information</title>
​
<style>
   body{
       background: lightblue;
       text-align: center;
  }
   h1{
       font-size: 30px;
       padding-top: 30px;
  }
   label,input{
       font-size: 20px;
      /* border-top: 20px;             padding-top: 20px;padding */
       margin-top: 15px;/*Margin */
       width: 180px;   /*Input box length*/
  }
   button{         /*Control button position, size and spacing*/
       font-size: 18px;
       margin-left: 50px;
       margin-right: -20px;
       /*border-radius: 10px;*/
       color: deepskyblue;
  }
   div{
       font-size: 20px;
  }
​
</style>
</head>
<body>
​
<h1>Please delete the information according to the student number</h1><br>
<form action="/delete/" method="post">
  {% csrf_token %}
<label>Student number:</label>
<input type="text" name="id" placeholder="Please enter student number">
<button type="submit" value="submit">determine</button>
</form>
<br>
<a href="/welcome">
   <button>Return to the main interface</button>
</a>
​
<div style="color: red"><br>
{% if err %}
{{ err }}
{% endif %}
</div>
<div>
{% if success %}
{{ success }}
{% endif %}
</div>
</body>
</html>

Back end part

def delete(request):
   if request.method == 'GET':
       return render(request, 'delete.html')
​
   id = request.POST.get('id', None)
   print(id)
   if id.isspace() == True:
       return render(request, 'delete.html', {'err': 'The student number cannot consist of spaces,Please re-enter!!!'})
   if len(id) == 0:
       return render(request, 'delete.html', {'err': 'Student number cannot be empty,Please re-enter!!!'})
   emp = models.StuInfo.objects.filter(id=id)
   if emp.count() == 0:
       return render(request, 'delete.html', {'err': 'The user does not exist,Please re-enter!!!'})
       models.StuInfo.objects.filter(id=id).delete()
       return render(request, 'delete.html', {'success': 'Delete succeeded'})

 

Realize the function of modifying student information

Front end part

As above, create an update template and add a route

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <title>Update information</title>
   <style>
   body{
       background: lightblue;
       text-align: center;
  }
   h1{
       font-size: 30px;
       padding-top: 30px;
  }
   label,input{
       font-size: 20px;
      /* border-top: 20px;             padding-top: 20px;padding */
       margin-top: 15px;/*Margin */
       width: 180px;   /*Input box length*/
  }
   button{         /*Control button position, size and spacing*/
       font-size: 25px;
       margin-left: 40px;
       margin-right: -30px;
       /*border-radius: 10px;*/
       color: deepskyblue;
       margin-top: 10px;
  }
​
</style>
</head>
<body>
<h1>Please modify the student information according to the student number</h1>
<form id="StuInfo" action="/update/"method="post">
  {% csrf_token %}
   <label>Student number:</label>
   <input name='id'placeholder="Please enter student ID"required autofocus="autofocus"><br>
   <label>full name:</label>
   <input name="stuname" placeholder="Please enter student name"><br>
   <label>Telephone:</label>
   <input name="stuphone" placeholder="Please enter student phone number"><br>
   <label>address:</label>
   <input name="stuaddress" placeholder="Please enter student address"><br>
   <label>Faculty:</label>
   <input name="stucollege" placeholder="Please enter the student Department"><br>
   <label>major:</label>
   <input name="stumajor" placeholder="Please enter student major"><br>
​
</form>
<p style="font-size: 25px">
{% if success %}
{{ success }}
{% endif %}
</p>
<p style="font-size: 25px; color: red">
{% if err %}
{{ err }}
{% endif %}
</p>
​
<a href="/welcome/">
   <button type="submit" style="font-size: 20px">return</button>
</a>
<button form="StuInfo" type="submit" style="font-size: 20px">determine</button>
​
</body>
</html>

Back end part

def update(request):
   if request.method =='GET':
       return render(request, 'update.html')
   list = ['id', 'stuname', 'stuphone', 'stuaddress', 'stucollege', 'stumajor']
   info = []
   for li in list:
       info.append(request.POST.get(li))
   if globals()['LoginId'] != 1:
       return render(request, 'update.html', {'err': 'Insufficient permissions, please switch to root User retry'})
   id = request.POST.get('id', None)
   if id.isspace() == True:
       return render(request, 'update.html', {'err': 'The student number cannot be composed of spaces,Please re-enter!'})
   s = models.StuInfo.objects.filter(id=info[0])
   if s.count() == 0:
       return render(request, 'update.html', {'err': 'This student information is not available and cannot be modified'})
   stu = models.StuInfo()
   stu.id = info[0]
   stu.stuname = info[1]
   stu.stuphone = info[2]
   stu.stuaddress = info[3]
   stu.stucollege = info[4]
   stu.stumajor = info[5]
   stu.save()
   return render(request, 'update.html', {'success': 'Student information modified successfully!'})

 

Realize the function of querying student information

Front end part

Query page select

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <title>Query information</title>
   <style>
   body{
       background: lightblue;
       text-align: center;
  }
   h1{
       font-size: 30px;
       padding-top: 20px;
  }
   label,input{
       font-size: 20px;
      /* border-top: 20px;             padding-top: 20px;padding */
       margin-top: 15px;/*Margin */
       width: 180px;   /*Input box length*/
       
  }
   button{         /*Control button position, size and spacing*/
       font-size: 20px;
       margin-left: 40px;
       margin-right: -20px;
       /*border-radius: 10px;*/
       color: deepskyblue;
  }
​
       
</style>
</head>
<body>
<div>
<h1>Query student information</h1>
<form action="/select/" method="post">
  {% csrf_token %}
   <label style="margin-left: 100px; ">Please inquire according to the student number:</label>
   <input name="id" placeholder="Please enter student ID" required>
   <button type="submit">query</button>
</form>
<br>
<a href="/login">
<button style="background-color: transparent;border-style: hidden;color: red">
  {% if error %}
      {{ error }}
  {% endif %}<br>
</button>
</a>
<label style="color: red">
  {% if err %}
      {{ err }}
  {% endif %}
  {% if success %}
      {{ success }}
  {% endif %}<br>
</label>
</div>
<div>
   <h1 style="margin-top: -20px">The query results are as follows</h1>
   <div style="font-size: 30px; margin-left: 700px; width:400px; text-align: left">
       <p> Student number:{{ id }}</p>
       <p>Student name:{{ stuname }}</p>
       <p>Student telephone:{{ stuphone }}</p>
       <p>Student address:{{ stuaddress }}</p>
       <p>Student Department:{{ stucollege }}</p>
       <p>Student major:{{ stumajor }}</p>
   </div>
​
<p>
<a href="/welcome">
   <button>Return to the main menu</button>
</a>
</p>
</div>
</body>
</html>

Back end part

def select(request):
   if request.method =='GET':
       return render(request, 'select.html')
   if globals()['LoginId'] != 1:
       return render(request, 'select.html', {'err': 'wrong root User, unable to view!'})
   #Get the id value from the form
   id = request.POST.get('id', None)
   #Determine the string type whose id cannot be empty
   if id.isspace() == True:
       return render(request, 'select.html', {'err': "Cannot be null,Please re-enter!"})
   #Assign the corresponding information to stu from the database according to the id value
   stu = models.StuInfo.objects.filter(id=id)
   if stu.count() == 0:
       return render(request, 'select.html', {'err': 'This student information is not queried. Please confirm whether to enter it into the system'})
   info = models.StuInfo.objects.values('id', 'stuname', 'stuphone', 'stuaddress', 'stucollege', 'stumajor').filter(id=id)[0]
   print("info=", info)
   return render(request, 'select.html', info)

 

Query all student information

front end

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <title>All information</title>
   <style>
       body{
           text-align: center;
      }
       label{
           align: center;
           font-size: 30px;
      }
       label2{
           font-size: 25px;
      }
​
   </style>
</head>
<body>
<h1>List of all student information</h1>
​
<table border="1" align="center"style="border-collapse: collapse; width: 1000px">
   <tr>
<th id="id">Student number</th>
<th>Student name</th>
<th>Student telephone</th>
<th>Student address</th>
<th>Student Department</th>
<th>Student major</th>
   </tr>
​
  {% for s in info %}
<tr>
<td id="id"> {{ s.id }}  </td>
<td> {{ s.stuname }}  </td>
<td> {{ s.stuphone }}  </td>
<td> {{ s.stuaddress }}  </td>
<td> {{ s.stucollege }}  </td>
<td> {{ s.stumajor }}  </td>
</tr>
  {% endfor %}
​
</table>
<br>
<a href="/welcome/">
   <button>return</button>
</a>
</body>
</html>

Back end code

def info(request):
   if request.method == 'POST':
       return render(request, 'info.html')
   info = models.StuInfo.objects.all()
   print(info)
   return render(request, 'info.html', {"info": info})

 

Effect display

 

 

 

 

 

 

Source file download: https://download.csdn.net/download/weixin_45971950/27882607

Topics: Python MySQL Django