赞
踩
创建数据库表
CREATE TABLE Class(
id INT PRIMARY KEY auto_increment,
class_name CHAR(20) NOT NULL
)charset utf8;
-- 学生表
CREATE TABLE Student(
id INT PRIMARY KEY auto_increment,
stu_name CHAR(20) NOT NULL,
class_id INT,
FOREIGN KEY(class_id) REFERENCES Class(id) on delete cascade on update cascade
)charset utf8;
-- 老师表
CREATE TABLE Teacher(
id INT PRIMARY KEY auto_increment,
th_name CHAR(20) NOT NULL
)charset utf8;
-- 老师和班级的关系表
CREATE TABLE relationship(
id INT PRIMARY KEY auto_increment,
t_id INT,
c_id INT,
FOREIGN KEY(t_id) REFERENCES Teacher(id) on delete cascade on update cascade,
FOREIGN KEY(c_id) REFERENCES Class(id) on delete cascade on update cascade
)charset utf8;
查看和添加、删除、修改班级
urls.py
from django.contrib import admin
from django.urls import path
from app import views
urlpatterns = [
path('classes',views.classes),
path('add_class',views.add_class),
path('del_class',views.del_class),
path('mod_class',views.mod_class),
views.py
from django.shortcuts import render,redirect
import pymysql
def classes(request):
# 2、建立连接对象
conn = pymysql.connect(host="localhost", user="root", password="1234567", database="python_db",charset='utf8')
# 3、创建游标对象
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
# 4、使用游标对象执行sql
# curor.execute(sql语句),返回值是影响的行数,如果是查询返回的查询到的总记录数
cursor.execute("select * from class")
class_list = cursor.fetchall()
# 7、关闭游标对象
cursor.close()
# 8、关闭连接
conn.close()
return render(request,'classes.html',{'class_list':class_list})
def add_class(request):
if request.method=="GET":
return render(request, 'add_class.html')
else:
v=request.POST.get('class_name')
conn=pymysql.connect(host="localhost",user='root',password='1234567',database='python_db',charset='utf8')
cursor=conn.cursor(cursor=pymysql.cursors.DictCursor)
cursor.execute("insert into class(class_name) values(%s)",v)
conn.commit()
cursor.close()
conn.close()
return redirect('/classes')
def del_class(request):
#拿删除发送的nid的值
nid=request.GET.get('nid')
conn=pymysql.connect(host="localhost",user='root',password='1234567',database='python_db',charset='utf8')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
cursor.execute("delete from class where id=%s", nid)
conn.commit()
cursor.close()
conn.close()
return redirect('/classes')
def mod_class(request):
if request.method=='GET':
nid = request.GET.get('nid')
conn = pymysql.connect(host="localhost", user='root', password='1234567', database='python_db', charset='utf8')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
cursor.execute("select id,class_name from class where id=%s",nid)
result=cursor.fetchone()
conn.commit()
cursor.close()
conn.close()
return render(request,'mod_class.html',{'result':result})
else:
nid=request.POST.get('id')
class_name=request.POST.get('class_name')
conn = pymysql.connect(host="localhost", user='root', password='1234567', database='python_db', charset='utf8')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
cursor.execute("update class set class_name=%s where id=%s",[class_name,nid])
conn.commit()
cursor.close()
conn.close()
return redirect('/classes')
classes.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>班级列表</h1>
<div>
<a href="/add_class">添加</a>
</div>
<table>
<thead>
<tr>
<th>id</th>
<th>班级名称</th>
<th>编辑</th>
</tr>
</thead>
<tbody>
{% for class in class_list %}
<tr>
<td>{{ class.id }}</td>
<td>{{ class.class_name }}</td>
<td>
<a href="/mod_class?nid={{ class.id }}">修改</a>
|
<a href="/del_class?nid={{ class.id }}">删除</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>
add_class.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>添加班级</h1>
<form method="post" action="/add_class">
<p>班级名称:<input type="text" name="class_name"/></p>
<input type="submit" value="提交">
</form>
</body>
</html>
mod_class.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>编辑班级</h1>
<form method="post" action="/mod_class">
<input style="display:none" type="text" value="{{ result.id }}" name='id'>
<p>班级名称:<input type="text" value="{{ result.class_name }}" name="class_name"></p>
<input type="submit" value="提交">
</form>
</body>
</html>
数据库封装
import pymysql
def get_one(sql,args):
conn = pymysql.connect(host="localhost", user="root", password="1234567", database="python_db",charset='utf8')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
cursor.execute(sql,args)
result = cursor.fetchone()
cursor.close()
conn.close()
return result
def get_list(sql,args):
conn = pymysql.connect(host="localhost", user="root", password="1234567", database="python_db",charset='utf8')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
cursor.execute(sql,args)
result = cursor.fetchall()
cursor.close()
conn.close()
return result
def modify(sql,args):
conn = pymysql.connect(host="localhost", user='root', password='1234567', database='python_db', charset='utf8')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
cursor.execute(sql,args)
conn.commit()
cursor.close()
conn.close()
views.py
def students(request):
conn = pymysql.connect(host="localhost", user="root", password="1234567", database="python_db",charset='utf8')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
cursor.execute('select student.id,student.student_name,class.class_name from student left join class on student.class_id=class.id;')
student_list=cursor.fetchall()
conn.commit()
conn.close()
cursor.close()
return render(request,'students.html',{'student_list':student_list})
def add_student(request):
if request.method == "GET":
conn = pymysql.connect(host="localhost", user='root', password='1234567', database='python_db', charset='utf8')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
cursor.execute("select * from class")
class_list = cursor.fetchall()
cursor.close()
conn.close()
return render(request,'add_student.html',{"class_list":class_list})
else:
student_name=request.POST.get("student_name")
class_id=request.POST.get("class_id")
conn = pymysql.connect(host="localhost", user='root', password='1234567', database='python_db', charset='utf8')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
cursor.execute("insert into student(student_name,class_id) values(%s,%s)",[student_name,class_id])
conn.commit()
cursor.close()
conn.close()
return redirect('/students')
def del_student(request):
nid = request.GET.get('nid')
conn = pymysql.connect(host="localhost", user='root', password='1234567', database='python_db', charset='utf8')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
cursor.execute("delete from student where id=%s", nid)
conn.commit()
cursor.close()
conn.close()
return redirect('/students')
from utils import sql
def mod_student(request):
if request.method=='GET':
nid=request.GET.get('nid')
class_list=sql.get_list("select * from class",[])
current_student=sql.get_one("select * from student where id=%s",nid)
return render(request,"mod_student.html",{'class_list':class_list,'current_student':current_student})
else:
nid = request.GET.get('nid')
student_name = request.POST.get('student_name')
class_id=request.POST.get('class_id')
sql.modify("update student set student_name=%s,class_id=%s where id=%s",[student_name,class_id,nid])
urls.py
urlpatterns = [
path('students',views.students),
path('add_student',views.add_student),
path('del_student',views.del_student),
path('mod_student',views.mod_student)
]
students.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>学生列表</h1>
<div >
<a href='/add_student'>添加</a>
</div>
<table>
<thead>
<tr>
<th>ID</th>
<th>姓名</th>
<th>班级</th>
<th>编辑</th>
</tr>
</thead>
<tbody>
{% for student in student_list %}
<tr>
<td>{{ student.id }}</td>
<td>{{ student.student_name }}</td>
<td>{{ student.class_name }}</td>
<td>
<a href="/mod_student?nid={{ student.id }}">修改</a>
|
<a href="/del_student?nid={{ student.id }}">删除</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>
add_student.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>添加学生</h1>
<form method="post" action="/add_student">
<p>学生名称:<input type="text" name="student_name"></p>
<p>
所属班级:
<select name="class_id">
{% for class in class_list %}
<option value="{{ class.id }}">{{ class.class_name }}</option>
{% endfor %}
</select>
</p>
<input type="submit" value="提交">
</form>
</body>
</html>
mod_student.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>编辑学生</h1>
<form method="post" action="/mod_student?nid={{ current_student.id }}">
<p>学生姓名:<input type="text" value="{{ current_student.student_name }} " name="student_name"></p>
<p>
所属班级:
<select name="class_id">
{% for class in class_list %}
{% if class.id == current_student.class_id %}
<option selected value="{{ class.id }}">{{ class.class_name }}</option>
{% else %}
<option value="{{ class.id }}">{{ class.class_name }}</option>
{% endif %}
{% endfor %}
</select>
</p>
<input type="submit" value="提交">
</form>
</body>
</html>
班级添加
views.py
def mod_add_class(request):
class_name=request.POST.get('class_name')
if len(class_name)>0:
sql.modify('insert into class(class_name) values(%s)',class_name)
return HttpResponse("ok");
else:
#如果输入为空,提示错误信息
return HttpResponse("添加信息不能为空")
urls.py
path('mod_add_class',views.mod_add_class)
classes.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.hide{
display: none;
}
.shadow{
position: fixed;
left: 0;
top: 0;
right: 0;
bottom: 0;
background-color: black;
opacity: 0.4;
z-index: 999;
}
.modal{
z-index: 1000;
position: fixed;
left: 50%;
top: 50%;
height: 300px;
width: 400px;
background-color: white;
margin-left:-200px;
margin-top: -150px;
}
</style>
</head>
<body>
<h1>班级列表</h1>
<div>
<a href="/add_class">添加</a>
<a onclick="showModal()">对话框添加</a>
</div>
<table>
<thead>
<tr>
<th>id</th>
<th>班级名称</th>
<th>编辑</th>
</tr>
</thead>
<tbody>
{% for class in class_list %}
<tr>
<td>{{ class.id }}</td>
<td>{{ class.class_name }}</td>
<td>
<a href="/mod_class?nid={{ class.id }}">修改</a>
|
<a href="/del_class?nid={{ class.id }}">删除</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
<div id="shadow"class="shadow hide"></div>
<div id="modal"class="modal hide">
<p>班级名称:
<input id="class_name" type="text" name="class_name">
</p>
<input type="button" value="提交" onclick="AjaxSend()">
<input type="button" value="取消" onclick="cancleModal()"><span id="errormsg"></span>
</div>
<script src="/static/jquery-3.5.1.js"></script>
<script>
function showModal(){
document.getElementById("shadow").classList.remove("hide")
document.getElementById('modal').classList.remove('hide')
}
function cancleModal() {
document.getElementById("shadow").classList.add("hide")
document.getElementById('modal').classList.add('hide')
}
function AjaxSend(){
$.ajax(
{
//data中的数据会以post的方式发送到url中
url:'/mod_add_class', //提交的地址
type:'POST', //提交方法
data:{'class_name':$('#class_name').val()}, //提交的数据
success:function (data){
//当服务端处理完成后,返回数据时,该函数会自动调用
//data是服务端返回的值
console.log(data)
if (data=='ok')
{
location.href='/classes'
}else{
$('#errormsg').text(data)
}
}
}
)
}
</script>
</body>
</html>
班级编辑
views.py
def mod_edit_class(request):
ret={'status':True,'message':None}
try:
nid=request.POST.get('nid')
class_name=request.POST.get('content')
sql.modify("update class set class_name=%s where id=%s",[class_name,nid])
except Exception as e:
ret['status']=False
ret['message']="处理异常"
return HttpResponse(json.dumps(ret))
urls.py
path('mod_edit_class',views.mod_edit_class)
classes.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.hide{
display: none;
}
.shadow{
position: fixed;
left: 0;
top: 0;
right: 0;
bottom: 0;
background-color: black;
opacity: 0.4;
z-index: 999;
}
.modal{
z-index: 1000;
position: fixed;
left: 50%;
top: 50%;
height: 300px;
width: 400px;
background-color: white;
margin-left:-200px;
margin-top: -150px;
}
</style>
</head>
<body>
<h1>班级列表</h1>
<div>
<a href="/add_class">添加</a>
<a onclick="showModal()">对话框添加</a>
</div>
<table>
<thead>
<tr>
<th>id</th>
<th>班级名称</th>
<th>编辑</th>
</tr>
</thead>
<tbody>
{% for class in class_list %}
<tr>
<td>{{ class.id }}</td>
<td>{{ class.class_name }}</td>
<td>
<a href="/mod_class?nid={{ class.id }}">修改</a>
|
<a onclick="modEdit(this)" >对话框修改</a>
|
<a href="/del_class?nid={{ class.id }}">删除</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
<div id="shadow"class="shadow hide"></div>
<div id="modal"class="modal hide">
<p>班级名称:
<input id="class_name" type="text" name="class_name">
</p>
<input type="button" value="提交" onclick="AjaxSend()">
<input type="button" value="取消" onclick="cancleModal()"><span id="errormsg"></span>
</div>
<div id="modEdit"class="modal hide">
<p>班级名称:
<input id="editId" type="text" name="id" style="display: none">
<input id="editClass_name" type="text" name="class_name">
</p>
<input type="button" value="提交" onclick="editAjaxSend()">
<input type="button" value="取消" onclick="cancleModal()"><span id="errormsg"></span>
</div>
<script src="/static/jquery-3.5.1.js"></script>
<script>
function showModal(){
document.getElementById("shadow").classList.remove("hide")
document.getElementById('modal').classList.remove('hide')
}
function cancleModal() {
document.getElementById("shadow").classList.add("hide")
document.getElementById('modal').classList.add('hide')
document.getElementById('modEdit').classList.add('hide')
}
function AjaxSend(){
$.ajax(
{
//data中的数据会以post的方式发送到url中
url:'/mod_add_class', //提交的地址
type:'POST', //提交方法
data:{'class_name':$('#class_name').val()}, //提交的数据
success:function (data){
//当服务端处理完成后,返回数据时,该函数会自动调用
//data是服务端返回的值
console.log(data)
if (data=='ok')
{
location.href='/classes'
}else{
$('#errormsg').text(data)
}
}
}
)
}
function modEdit(ths){
document.getElementById("shadow").classList.remove("hide")
document.getElementById('modEdit').classList.remove('hide')
/*
获取当前点击标签
当前标签父标签,再找其上方标签
获取当前行班级名称,赋值到编辑对话框
*/
var row=$(ths).parent().prevAll()
var content=$(row[0]).text() //获取班级的名称
$('#editClass_name').val(content) //把班级名称赋值到 对话框中
var contendId=$(row[1]).text()
$('#editId').val(contendId)
}
function editAjaxSend(){
//用户输入的值
var nid=$('#editId').val()
var content=$('#editClass_name').val()
$.ajax({
url: "/mod_edit_class",
type: "POST",
data: {'nid':nid,'content':content},
success:function (arg){
arg=JSON.parse(arg)
if(arg.status){
location.reload() //reload 当前页面刷新
}else
{
alert(arg.message)
}
}
})
}
</script>
</body>
</html>
学生的添加和修改
views.py
def mod_add_student(request):
ret={'status':True,'message':None}
try:
#获取用户提交的数据
student_name=request.POST.get('student_name')
class_id=request.POST.get("class_id")
sql.modify('insert into student(student_name,class_id) values(%s,%s)',[student_name,class_id,])
except Exception as e:
ret['status']=False
ret['message']=str(e)
return HttpResponse(json.dumps(ret))
def mod_edit_student(request):
ret = {'status': True, 'message': None}
try:
nid=request.POST.get('nid')
name=request.POST.get('name')
classId=request.POST.get('classId')
sql.modify('update student set student_name=%s,class_id=%s where id=%s',[name,classId,nid])
except Exception as e:
ret['status'] = False
ret['message'] = str(e)
return HttpResponse(json.dumps(ret))
urls.py
path('mod_add_student',views.mod_add_student),
path('mod_edit_student',views.mod_edit_student)
student.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.shadow{
position:fixed;
background-color: black;
top: 0;
left: 0;
right: 0;
bottom: 0;
opacity: 0.4;
z-index: 999;
}
.add_modal{
position: fixed;
background-color: white;
top: 50%;
left: 50%;
width: 400px;
height: 400px;
z-index: 1000;
margin-left:-200px;
margin-top: -150px;
}
.hide{
display: none;
}
</style>
</head>
<body>
<h1>学生列表</h1>
<div >
<a href='/add_student'>添加</a>
<a id="modAdd" >对话框添加</a>
</div>
<table>
<thead>
<tr>
<th>ID</th>
<th>姓名</th>
<th>班级</th>
<th>编辑</th>
</tr>
</thead>
<tbody>
{% for student in student_list %}
<tr>
<td>{{ student.id }}</td>
<td>{{ student.student_name }}</td>
<td clsId="{{ student.class_id }}" >{{ student.class_name }}</td>
<td>
<a href="/mod_student?nid={{ student.id }}">修改</a>
|
<a class="btn_edit">对话框编辑</a>
|
<a href="/del_student?nid={{ student.id }}">删除</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
<div id="shadow" class="hide shadow"></div>
<div id="add_modal" class="add_modal hide">
<p>
姓名:<input id="add_student_name" name="student_name" placeholder="姓名" type="text">
</p>
<p>
班级:<select id="addClassId" name="classId">
{% for class in class_list %}
<option value="{{ class.id }}">{{ class.class_name }}</option>
{% endfor %}
</select>
</p>
<input id="btnAdd" type="button" value="添加">
<span id="addError" style="color: red"></span>
</div>
<div id="edit_modal" class="add_modal hide">
<h3>编辑学生信息</h3>
<p>
姓名:<input id="editStudentName" name="editStudentName" placeholder="姓名" type="text">
<input type="text" id="editId" style="display: none">
</p>
<p>
班级:<select id="editClassId" name="classId">
{% for class in class_list %}
<option value="{{ class.id }}">{{ class.class_name }}</option>
{% endfor %}
</select>
</p>
<input id="btnEdit" type="button" value="修改">
<span id="editError" style="color: red"></span>
</div>
<script src="/static/jquery-3.5.1.js"></script>
<script>
$(function (){
$('#modAdd').click(function (){
$('#shadow,#add_modal').removeClass('hide')
})
$('#btnAdd').click(function (){
$.ajax({
url:'/mod_add_student',
type:'POST',
data:{'student_name':$('#add_student_name').val(),'class_id':$('#addClassId').val()},
//arg获取后端返回来的值 return HttpResponse(json.dumps(ret))
success:function (arg){
//将字符串转化成对象
arg=JSON.parse(arg)
if(arg.status)
{
location.reload()
}else
{
$('#addError').text(arg.message)
}
}
})
})
$('.btn_edit').click(function (){
$('#shadow,#edit_modal').removeClass('hide')
/* 获取当前标签
再获取当前标签的父标签
$(this)表示当前标签
$(this).parent().prevAll()表示当前标签的父标签前面所有的标签
*/
var tds=$(this).parent().prevAll()
//获取学生ID
var studentId=$(tds[2]).text()
//获取学生姓名
var studentName=$(tds[1]).text()
//获取班级ID
var classId=$(tds[0]).attr('clsid')
$('#editId').val(studentId)
$('#editStudentName').val(studentName)
$('#editClassId').val(classId)
})
$('#btnEdit').click(function (){
var nid=$('#editId').val()
var name=$('#editStudentName').val()
var classId=$('#editClassId').val()
$.ajax({
url: "/mod_edit_student",
type: "POST",
data:{'nid':nid,'name':name,'classId':classId},
dataType:'JSON', //将data转化为对象
success:function (arg){
if(arg.status){
location.reload()
}else{
$('#editError').text(arg.message)
}
}
})
})
})
</script>
</body>
</html>
增删改
views.py
def teachers(request):
# teacher_list=sql.get_list('select * from teacher',[])
teacher_list=sql.get_list('''
SELECT teacher.id as tid,teacher.teacher_name,class.class_name from teacher
left join class_teacher on teacher.id=class_teacher.teacher_id
left join class on class.id=class_teacher.class_id;''',[])
result={}
#将老师所任教的班级整合到一个列表中
for row in teacher_list:
tid = row['tid']
if tid in result:
result[tid]['class_names'].append(row['class_name'])
else:
result[tid] = {'tid': row['tid'], 'teacher_name': row['teacher_name'], 'class_names': [row['class_name']]}
return render(request,'teachers.html',{'teacher_list':result.values()})
def add_teacher(request):
if request.method == "GET":
class_list=sql.get_list("select * from class",[])
return render(request, 'add_teacher.html',{"class_list":class_list})
else:
teacher_name=request.POST.get('teacher_name')
class_ids=request.POST.getlist('class_ids')
print(teacher_name,class_ids)
#老师表中添加数据
teacher_id=sql.create("insert into teacher(teacher_name) values(%s)",[teacher_name,])
#老师和班级的关系表中添加数据
#插入多条数据不建议直接使用modify这种方法,会多次进行数据库的开启和关闭
# for classId in class_ids:
# sql.modify("insert into class_teacher(class_id,teacher_id) values(%s,%s)",[classId,teacher_id])
#一次连接,多次提交
# obj=sql.Sql()
# for classId in class_ids:
# obj.modify("insert into class_teacher(class_id,teacher_id) values(%s,%s)",[classId,teacher_id])
# obj.close()
#一次连接,一次提交
data_list=[]
for classId in class_ids:
temp=(classId,teacher_id)
data_list.append(temp)
obj=sql.Sql()
obj.multiple_motify('insert into class_teacher(class_id,teacher_id) values(%s,%s)',data_list)
obj.close()
return redirect('/teachers')
#修改教师的信息
def mod_teacher(request):
#这段是获取前端页面传过来的信息,并把前端的需要的信息传过去
if request.method=="GET":
#先从页面取用户的nid
nid=request.GET.get('nid')
obj=sql.Sql()
#获取当前要修改老师的信息
teacher_info=obj.get_one("select * from teacher where id=%s",[nid,])
print(teacher_info)
#获取当前老师所有的课程id
class_id_list=obj.get_list("select class_id from class_teacher where teacher_id=%s",[nid,])
temp=[]
for i in class_id_list:
#将保存在字典中的老师所教的班级id 保存到列表中,以至于前端页面好取值
temp.append(i['class_id'])
#获取所有的班级信息,以便于让修改时选择老师所任教的班级
class_list=obj.get_list("select * from class ",[])
class_list
obj.close()
#print(teacher_info,class_id_list,class_list)
return render(request,"mod_teacher.html",{'teacher_info':teacher_info,'class_id_list':temp,'class_list':class_list})
#这段是将前端页面的修改好的教师信息在数据库进行修改
else:
#获取前端修改的值
#获取前端传过来的老师id,使其知道对哪位老师进行修改
nid=request.GET.get("nid")
#获取老师姓名修改后的值
teacher_name=request.POST.get('teacher_name')
#获取老师班级修改后的值
class_ids=request.POST.getlist("class_ids")
#更新老师表
obj=sql.Sql()
obj.modify("update teacher set teacher_name=%s where id=%s",[teacher_name,nid])
#更新老师和班级的关系表
#先把当前老师和班级对应关系删除,然后再添加
obj.modify('delete from class_teacher where teacher_id=%s',[nid,])
#存放老师id和修改后任教的班级id
data_list=[]
for cls_id in class_ids:
temp=(nid,cls_id,)
data_list.append(temp)
obj.multiple_motify('insert into class_teacher(teacher_id,class_id) values(%s,%s)',data_list)
obj.close()
return redirect('/teachers')
def del_teacher(request):
nid=request.GET.get('nid')
obj=sql.Sql()
# 先把当前老师和班级对应关系删除,然后再删除老师
obj.modify('delete from class_teacher where teacher_id=%s', [nid,])
obj.modify("delete from teacher where id=%s",[nid,])
obj.close()
return redirect('/teachers')
urls.py
path('teachers',views.teachers),
path('add_teacher',views.add_teacher),
path('mod_teacher',views.mod_teacher),
path('del_teacher',views.del_teacher),
teachers.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</style>
</head>
<body>
<h1>老师列表</h1>
<a href="/add_teacher">添加</a>
<table border="1">
<thead>
<tr>
<th>id</th>
<th>老师姓名</th>
<th>任教班级</th>
<th>编辑</th>
</tr>
</thead>
<tbody>
{% for teacher in teacher_list %}
<tr>
<td>{{ teacher.tid }}</td>
<td>{{ teacher.teacher_name }}</td>
<td>
{% for class_name in teacher.class_names %}
<span >{{ class_name }}</span>
,
{% endfor %}
</td>
<td>
<a href="/mod_teacher?nid={{ teacher.tid }}">修改</a>
|
<a href="/del_teacher?nid={{ teacher.tid }}">删除</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>
add.teacher.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>添加教师</h1>
<form method="post" action="/add_teacher">
<p>教师姓名:<input type="text" name="teacher_name"/></p>
任教班级:
{# name='xxx' 用于提交到后台 #}
<select multiple size="10" name="class_ids">
{% for class in class_list %}
<option value="{{ class.id }}">{{ class.class_name }}</option>
{% endfor %}
</select>
<p><input type="submit" value="提交"></p>
</form>
</body>
</html>
</body>
</html>
mod_teacher.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>编辑老师</h1>
{# ?nid={{ teacher_info.teacher_id }} 提交后让后端只知道更新谁的信息 #}
<form method="post" action="/mod_teacher?nid={{ teacher_info.id}}">
{#当前老师的名称默认填写到输入框中#}
<p><input type="text" name="teacher_name" value="{{ teacher_info.teacher_name }}"></p>
<p>
{# 使用name='xxx' 能够让后端进行取值操作 #}
<select name="class_ids" multiple size="10">
{% for class in class_list %}
{#如果class.id 在当前老师任教的班级id中,option加上selected#}
{% if class.id in class_id_list%}
<option value="{{ class.id }}" selected> {{ class.class_name }}</option>
{% else %}
{#否则不加selected#}
<option value="{{ class.id }}" > {{ class.class_name }}</option>
{% endif %}
{% endfor %}
</select>
</p>
{#button是普通的按钮,submit是提交按钮,submit是普通按钮的一个特例#}
<input type="submit" value="提交">
</form>
</body>
</html>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。