專案準備
建立專案
django-admin startproject Mydjango
cd Mydjango
python manage.py startapp APP
專案架構
Mydjango
APP
migrations
0001_initial.py
static
style.css
templates
index.html [首頁入口頁面]
add_classes.html [新增班級頁面]
add_students.html [新增學生頁面]
add_teachers.html [新增老師頁面]
edit_classes.html [編輯班級頁面]
edit_students.html [編輯學生頁面]
edit_teachers.html [編輯老師頁面]
get_classes.html [班級展示頁面]
get_students.html [學生展示頁面]
get_teachers.html [老師展示頁面]
set_teacher.html [班級分配老師頁面]
views
index.py [首頁檢視]
classes.py [班級檢視]
students.py [學生檢視]
teachers.py [老師檢視]
admin.py
apps.py
models.py
tests.py
Mydjango
settings.py
urls.py
wsgi.py
db.sqlite3
manage.py
static
style.css
*{margin: auto;}
a,table {text-decoration:none; padding: 10px}
thead {font-size: 18px;}
table {border-spacing:0;border-collapse:collapse;background:lightskyblue; text-align: center;margin-top: 20px;}
table > th,td{padding: 5px 20px;}
.list_top{width: 200px; font-size: 30px;font-weight:bold;margin-top: 30px;}
templates
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>學生管理系統</title>
<style>
*{margin: auto;text-align: center;}
h1{margin-top: 10%;margin-bottom: 30px;}
div{margin-top: 50px;}
div>a {text-decoration:none;margin: 10px;padding: 15px;background: lightskyblue;border-radius:10px; -moz-border-radius:10px;}
</style>
</head>
<body>
<h1>PythonDjango框架練習-學生管理系統</h1>
<div>
<a href="classes.html">班級展示頁面</a>
<a href="teachers.html">老師展示頁面</a>
<a href="students.html">學生展示頁面</a>
</div>
</body>
</html>
add_classes.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>新增班級</title>
</head>
<body>
<form action="add_classes.html" method="POST">
{% csrf_token %}
<input type="text" name="title"/>
<input type="submit" value="提交"/>
</form>
</body>
</html>
add_students.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>新增學生</title>
</head>
<body>
<form action="/add_students.html" method="POST">
{% csrf_token %}
<p><input type="text" name="username" placeholder="姓名" value=""/></p>
<p><input type="text" name="age" placeholder="年齡"/></p>
<p>
男:<input type="radio" name="gender" value="1">
女:<input type="radio" name="gender" value="0">
</p>
<p>
<select name="cs">
<!--迴圈顯示班級列表id和名稱-->
{% for row in cs_list %}
<option value="{{ row.id }}">{{ row.titile }}</option>
{% endfor %}
</select>
</p>
<input type="submit" value="提交"/>
</form>
</body>
</html>
add_teachers.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>新增老師</title>
</head>
<body>
<form action="/add_teachers.html" method="POST">
{% csrf_token %}
<p><input type="text" name="name" placeholder="姓名"/></p>
<p><input type="text" name="age" placeholder="年齡"/></p>
<p>
男:<input type="radio" name="gender" value="1">
女:<input type="radio" name="gender" value="0">
</p>
<input type="submit" value="提交"/>
</form>
</body>
</html>
edit_classes.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>編輯班級</title>
</head>
<body>
<!--將id和修改數值一併提交-->
<form method="POST" action="/edit_classes.html">
{% csrf_token %}
<!-- value值為後臺查詢到的物件[需要編輯的id和值] -->
<input type="text" name="id" value="{{ obj.id }}" style="display: none"/>
<input type="text" name="con" value="{{ obj.titile }}"/>
<input type="submit" value="提交"/>
</form>
</body>
</html>
edit_students.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>編輯學生</title>
</head>
<body>
<form action="/edit_students.html" method="POST">
{% csrf_token %}
<p style="display: none">
<!--隱藏id項-->
<input typpe="text" name="nid" value="{{ obj.id }}">
</p>
<p><input type="text" name="username" placeholder="姓名" value="{{ obj.username }}"/></p>
<p><input type="text" name="age" placeholder="年齡" value="{{ obj.age }}"/></p>
<p>
{% if obj.gender %}
<!--判斷性別單選項-->
男:<input type="radio" name="gender" value="1" checked="checked"/>
女:<input type="radio" name="gender" value="0" />
{% else %}
男:<input type="radio" name="gender" value="1" />
女:<input type="radio" name="gender" value="0" checked="checked"/>
{% endif %}
</p>
<p>
<select name="cs_list">
<!--迴圈班級列表-->
{% for row in cs_list %}
<!--迴圈判斷原有的id和名稱-->
{% if row.id == obj.cs_id %}
<option value="{{ row.id }}" selected="selected">{{ row.titile }}</option>
{% else %}
<option value="{{ row.id }}" >{{ row.titile }}</option>
{% endif %}
{% endfor %}
</select>
</p>
<input type="submit" value="提交"/>
</form>
</body>
</html>
edit_teachers.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>編輯老師</title>
</head>
<body>
<form action="/edit_teachers.html" method="POST">
{% csrf_token %}
<p style="display: none">
<!--隱藏id項-->
<input typpe="text" name="nid" value="{{ obj.id }}">
</p>
<p><input type="text" name="name" placeholder="姓名" value="{{ obj.name }}"/></p>
<p><input type="text" name="age" placeholder="年齡" value="{{ obj.age }}"/></p>
<p>
{% if obj.gender %}
<!--判斷性別單選項-->
男:<input type="radio" name="gender" value="1" checked="checked"/>
女:<input type="radio" name="gender" value="0" />
{% else %}
男:<input type="radio" name="gender" value="1" />
女:<input type="radio" name="gender" value="0" checked="checked"/>
{% endif %}
</p>
<input type="submit" value="提交"/>
</form>
</body>
</html>
get_classes.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>班級頁面</title>
<link href="static/style.css" rel="stylesheet">
</head>
<body>
<div class="list_top">
<a href="add_classes.html">新增班級</a>
</div>
<table border="1">
<thead>
<th>序列號</th>
<th>名稱</th>
<th>任課老師</th>
<th>操作</th>
</thead>
<tbody>
{% for row in cls_list %}
<!--迴圈班級列表-->
<tr>
<td>
{{ row.id }}
<!--獲取班級列表id欄位-->
</td>
<td>
{{ row.titile }}
<!--獲取班級列表title欄位-->
</td>
<td>
<!--{{ row.m.all }}為當前班級所有任課老師的物件,迴圈並取老師名字展示【和分配頁面取法略有差異】-->
{% for item in row.m.all %}
<span>{{ item.name }}</span>
{% endfor %}
</td>
<th>
<!--傳引數nid={{row.id}}到後端,避免使用全域性id-->
<a href="/edit_classes.html?nid={{ row.id }}">編輯</a>|
<a href="/del_classes.html?nid={{ row.id }}">刪除</a>|
<a href="/set_teacher.html?nid={{ row.id }}">分配老師</a>
</th>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>
get_students.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>學生頁面</title>
<link href="static/style.css" rel="stylesheet">
</head>
<body>
<div class="list_top">
<a href="add_students.html">新增學生</a>
</div>
<table border="1">
<thead>
<th>序列號</th>
<th>姓名</th>
<th>年齡</th>
<th>性別</th>
<th>班級</th>
<th>操作</th>
</thead>
<tbody>
{% for row in stu_list %}
<!--迴圈學生列表-->
<tr>
<td>
{{ row.id }}
<!--獲取學生列表id欄位-->
</td>
<td>
{{ row.username }}
<!--獲取學生列表姓名欄位-->
</td>
<td>
{{ row.age }}
<!--獲取學生列表年齡欄位-->
</td>
<td>
<!--根據布林值判斷性別-->
{% if row.gender == True %}
男
{% else %}
女
{% endif %}
<!--獲取學生列表性別欄位-->
</td>
<td>
{{ row.cs.titile }}
<!--獲取學生列表班級欄位-->
</td>
<th>
<!--傳引數nid={{row.id}}到後端,避免使用全域性id-->
<a href="/edit_students.html?nid={{ row.id }}">編輯</a>|
<a href="/del_students.html?nid={{ row.id }}">刪除</a>
</th>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>
get_teachers.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>老師頁面</title>
<link href="static/style.css" rel="stylesheet">
</head>
<body>
<div class="list_top">
<a href="add_teachers.html">新增老師</a>
</div>
<table border="1">
<thead>
<th>序列號</th>
<th>姓名</th>
<th>年齡</th>
<th>性別</th>
<th>操作</th>
</thead>
<tbody>
{% for row in tea_list %}
<!--迴圈老師列表-->
<tr>
<td>
{{ row.id }}
<!--獲取老師列表id欄位-->
</td>
<td>
{{ row.name }}
<!--獲取老師列表姓名欄位-->
</td>
<td>
{{ row.age }}
<!--獲取老師列表年齡欄位-->
</td>
<td>
<!--根據布林值判斷性別-->
{% if row.gender == True %}
男
{% else %}
女
{% endif %}
<!--獲取老師列表性別欄位-->
</td>
<th>
<!--傳引數nid={{row.id}}到後端,避免使用全域性id-->
<a href="/edit_teachers.html?nid={{ row.id }}">編輯</a>|
<a href="/del_teachers.html?nid={{ row.id }}">刪除</a>
</th>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>
set_teacher.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>分配老師</title>
</head>
<body>
<form method="POST" action="/set_teacher.html?nid={{ nid }}">
{% csrf_token %}
<p>當前班級老師:
{% for itum in cs_tea_list %}
{{ itum }}
{% endfor %}
</p>
<p>
<strong>需要修改請在以下欄目中選擇並提交【支援多選】</strong>
</p>
<select multiple name="teacher_ids">
{% for item in all_teacher_list %}
{% if item in all_reacher_list %}
<option value="{{ item.id }}" selected="selected">{{ item.name }}</option>
{% else %}
<option value="{{ item.id }}">{{ item.name }}</option>
{% endif %}
{% endfor %}
</select>
<input type="submit" value="提交">
</form>
</body>
</html>
views
classes.py
# -*- coding:utf8 -*-
from django.shortcuts import render,redirect
from APP import models
def get_classes(request): #檢視班級
cls_list = models.Classes.objects.all() #班級表所有資料
return render(request,'get_classes.html',{'cls_list':cls_list}) #返回班級表所有資料
def add_classes(request): #新增班級
if request.method == "GET": #判斷提交方式是否為GET
return render(request, 'add_classes.html') #返回新增頁面
elif request.method == "POST": #判斷提交方式是否為POST
title = request.POST.get('title') #獲取班級名稱
models.Classes.objects.create(titile=title) #建立新的班級
return redirect('/classes.html') #返回班級列表
def del_classes(request): #刪除班級
nid = request.GET.get('nid') #獲取要刪除的班級id
models.Classes.objects.filter(id=nid).delete() #刪除班級
return redirect('/classes.html') #返回班級列表
def edit_classes(request): #編輯班級
if request.method == "GET": #判斷提交方式是否為GET
nid = request.GET.get('nid') #獲取編輯列的id
obj = models.Classes.objects.filter(id=nid).first() #獲取編輯列的值
return render(request,'edit_classes.html',{'obj':obj}) #返回編輯頁面,並附加要修改的值
elif request.method == "POST": #判斷提交方式是否為POST
nid = request.POST.get("id") #獲取編輯列的id
title = request.POST.get("con") #獲取編輯列的名稱
models.Classes.objects.filter(id=nid).update(titile=title) #更新資料
return redirect('/classes.html') #返回班級頁面
def set_teacher(request):
if request.method == 'GET':
nid = request.GET.get('nid') #獲取當前要分配老師的班級id
all_teacher_list = models.Teachers.objects.all() #獲取所有老師
cls_obj = models.Classes.objects.filter(id=nid).first() #獲取班級id對應的物件
print("班級ID物件",cls_obj)
cs_tea_list=cls_obj.m.all() #獲取當前班級的老師
print("當前班級老師,不帶ID用於展示",cs_tea_list)
cls_teacher_list = cls_obj.m.all().values_list('id','name') #獲取當前班級老師的id和姓名,班級物件多對多關係正向查詢
print("當前班級老師帶ID,用於查詢和選擇", cls_teacher_list)
id_list = list(zip(*cls_teacher_list))[0] if list(zip(*cls_teacher_list)) else [] #zip格式化函式進行壓縮格式化便於取值
print("當前班級老師ID",id_list)
return render(request,'set_teacher.html', #返回當前班級的老師和所有老師
{
'cls_teacher_list':id_list,
'all_teacher_list':all_teacher_list,
'nid':nid,
"cs_tea_list":cs_tea_list
})
elif request.method == "POST":
nid = request.GET.get('nid') #當前編輯修改的ID
print("當前編輯修改的ID",nid)
ids = request.POST.getlist('teacher_ids') #分配的老師ID
print("當前分配的老師ID",ids)
obj = models.Classes.objects.filter(id=nid).first() #獲取班級id對應的物件
obj.m.set(ids) #修改分配老師
return redirect('/classes.html')
index.py
# -*- coding:utf8 -*-
from django.shortcuts import render,redirect
from APP import models
def portal(request):
return render(request, 'index.html')
students.py
# -*- coding:utf8 -*-
from django.shortcuts import render,redirect
from APP import models
def get_students(request): #學生資訊展示
stu_list = models.Students.objects.all() #顯示所有學生列表
return render(request,'get_students.html',{'stu_list':stu_list}) #返回學生頁面,附加所有學生列表引數
def add_students(request): #學生資訊新增
if request.method == 'GET': #判斷提交方式
cs_list = models.Classes.objects.all() #獲取班級列表,用於新增學生班級下拉選單
return render(request,'add_students.html',{'cs_list':cs_list}) #返回新增學生頁面,附加所有班級下拉選單
elif request.method == 'POST': #判斷提交方式
u = request.POST.get('username') #獲取填寫姓名
a = request.POST.get('age') #獲取填寫年齡
g = request.POST.get('gender') #獲取選擇性別
c = request.POST.get('cs') #獲取選擇班級
#獲取的欄位內容新增到資料庫
models.Students.objects.create(
username=u,
age=a,
gender=g,
cs_id=c
)
return redirect('/students.html') #跳轉到學生資訊頁面
def del_students(request): #學生資訊刪除
nid = request.GET.get('nid') #獲取要刪除的學生id
models.Students.objects.filter(id=nid).delete() #刪除選中學生
return redirect('/students.html') #刪除後重新整理跳轉到學生資訊頁面
def edit_students(request): #學生資訊修改
if request.method == "GET": #判斷提交方式是否為GET
nid = request.GET.get('nid') #獲取編輯列的id
obj = models.Students.objects.filter(id=nid).first() #獲取編輯列的值
cs_list = models.Classes.objects.values('id','titile') #獲取班級列表id和名稱,用於修改學生班級下拉選單
return render(request,'edit_students.html',{'obj':obj,'cs_list':cs_list}) #返回編輯頁面,並附加要修改的值
elif request.method == "POST": #判斷提交方式是否為POST
nid = request.POST.get("nid") #獲取編輯列的id
u = request.POST.get("username") #獲取編輯列的姓名
a = request.POST.get("age") #獲取編輯列的年齡
g = request.POST.get("gender") #獲取編輯列的性別
class_id = request.POST.get("cs_list") #獲取編輯列的班級
models.Students.objects.filter(id=nid).update(username=u,age=a,gender=g,cs_id=class_id) #更新資料
return redirect('/students.html') #返回班級頁面
teachers.py
# -*- coding:utf8 -*-
from django.shortcuts import render,redirect
from APP import models
def get_teachers(request): # 老師資訊展示
tea_list = models.Teachers.objects.all() # 獲取所有老師列表
return render(request, 'get_teachers.html', {'tea_list': tea_list}) # 返回老師頁面,附加所有老師列表引數
def add_teachers(request): # 老師資訊新增
if request.method == 'GET': # 判斷提交方式
return render(request, 'add_teachers.html') # 返回新增老師頁面
elif request.method == 'POST': # 判斷提交方式
u = request.POST.get('name') # 獲取填寫姓名
a = request.POST.get('age') # 獲取填寫年齡
g = request.POST.get('gender') # 獲取選擇性別
# 獲取的欄位內容新增到資料庫
models.Teachers.objects.create(
name=u,
age=a,
gender=g,
)
return redirect('/teachers.html') # 跳轉到老師資訊頁面
def del_teachers(request): # 老師資訊刪除
nid = request.GET.get('nid') # 獲取要刪除的老師id
models.Teachers.objects.filter(id=nid).delete() # 刪除選中老師
return redirect('/teachers.html') # 刪除後重新整理跳轉到老師資訊頁面
def edit_teachers(request): # 老師資訊修改
if request.method == "GET": #判斷提交方式是否為GET
nid = request.GET.get('nid') #獲取編輯列的id
obj = models.Teachers.objects.filter(id=nid).first() #獲取編輯列的值
cs_list = models.Classes.objects.values('id','titile') #獲取班級列表id和名稱,用於修改學生班級下拉選單
return render(request,'edit_teachers.html',{'obj':obj,'cs_list':cs_list}) #返回編輯頁面,並附加要修改的值
elif request.method == "POST": #判斷提交方式是否為POST
nid = request.POST.get("nid") #獲取編輯列的id
u = request.POST.get("name") #獲取編輯列的姓名
a = request.POST.get("age") #獲取編輯列的年齡
g = request.POST.get("gender") #獲取編輯列的性別
models.Teachers.objects.filter(id=nid).update(name=u,age=a,gender=g) #更新資料
return redirect('/teachers.html') #返回班級頁面
admin.py
系統預設未變動
apps.py
from django.apps import AppConfig
class AppConfig(AppConfig):
name = 'APP'
models.py
# -*- coding:utf8 -*-
from django.db import models
class Classes(models.Model):
"""
班級表
"""
titile = models.CharField(max_length=32) #班級名稱
m = models.ManyToManyField("Teachers") #班級和老師【多對多關係表】
class Teachers(models.Model):
"""
教師表
"""
name = models.CharField(max_length=32) #姓名
age = models.IntegerField() #年齡
gender = models.BooleanField() #性別
class Students(models.Model):
"""
學生表
"""
username = models.CharField(max_length=32) #姓名
age = models.IntegerField() #年齡
gender = models.BooleanField() #性別
cs = models.ForeignKey("Classes",on_delete=models.CASCADE,) #學生和班級【一對多關係表】
Mydjango
settings.py
INSTALLED_APPS
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'APP',
]
TEMPLATES
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'APP/templates')],
'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',
],
},
},
]
DATABASES
實驗環境使用sqlite3資料庫,可根據自身需求變更為其它資料庫
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
LANGUAGE_CODE
LANGUAGE_CODE = 'zh-hans'
STATIC_URL
STATIC_URL = '/static/'
STATICFILES_DIRS
STATICFILES_DIRS=(
os.path.join(BASE_DIR,"APP/static"),
)
urls.py
# -*- coding:utf8 -*-
from django.contrib import admin
from django.urls import path,re_path
from APP.views import index,classes,students,teachers
urlpatterns = [
path('admin/', admin.site.urls), # admin管理後臺
re_path('^$',index.portal), # 首頁
re_path('^classes.html$', classes.get_classes), # 班級頁面
re_path('^add_classes.html$', classes.add_classes), # 新增班級
re_path('^del_classes.html$', classes.del_classes), # 刪除班級
re_path('^edit_classes.html$', classes.edit_classes), # 編輯班級
re_path('^set_teacher.html$', classes.set_teacher), # 分配老師
re_path('^students.html$', students.get_students), # 學生頁面
re_path('^add_students.html$', students.add_students), # 新增學生
re_path('^del_students.html$', students.del_students), # 刪除學生
re_path('^edit_students.html$', students.edit_students),# 編輯學生
re_path('^teachers.html$', teachers.get_teachers), # 老師頁面
re_path('^add_teachers.html$', teachers.add_teachers), # 新增老師
re_path('^del_teachers.html$', teachers.del_teachers), # 刪除老師
re_path('^edit_teachers.html$', teachers.edit_teachers),# 編輯老師
]
測試
生成資料表
python manage.py makemigrations APP
python manage.py migrate
執行服務訪問測試
python manage.py runserver