1. views.py
################################# teacher_class 多对多########################################
#老师班级
@wapper
def teacher_class(request):
result = sqlhelper.get_list(
""" select teachers.id,teachers.name,classes.title from teachers
left join teacher_class on teachers.id = teacher_class.teacher_id
left join classes on teacher_class.class_id = classes.id
""", [])
# print(result)
# [
# {'id': 1, 'name': '张三', 'title': '全栈1期'},
# {'id': 1, 'name': '张三', 'title': '全栈2期'},
# {'id': 2, 'name': '李四', 'title': '全栈2期'},
# {'id': 2, 'name': '李四', 'title': 'java'},
# {'id': 3, 'name': '小明', 'title': 'java'},
# {'id': 3, 'name': '小明', 'title': 'mysql'},
# {'id': 3, 'name': '小明', 'title': 'linux'}
# ]
#设计
dic = {}
for row in result:
tid = row['id']
if tid not in dic:
dic[tid] = {'id': row['id'], 'name': row['name'], 'titles': [row['title']]}
else:
dic[tid]['titles'].append(row['title'])
# print(dic)
# {
# 1: {'id': 1, 'name': '张三', 'titles': ['全栈1期', '全栈2期']},
# 2: {'id': 2, 'name': '李四', 'titles': ['全栈2期', 'java']},
# 3: {'id': 3, 'name': '小明', 'titles': ['java', 'mysql', 'linux']}
# }
# print(dic.values())
# [
# {'id': 1, 'name': '张三', 'titles': ['全栈1期', '全栈2期']},
# {'id': 2, 'name': '李四', 'titles': ['全栈2期', 'java']},
# {'id': 3, 'name': '小明', 'titles': ['java', 'mysql', 'linux']}
# ]
return render(request, 'teacher_class.html', {'result': dic.values()})
#添加老师班级
@wapper
def add_teacher_class(request):
if request.method == 'GET':
obj = sqlhelper.Sqlhelper() # 实例化对象
classes = obj.get_list('select id,title from classes',[])
obj.close()
return render(request,'add_teacher_class.html',{'classes':classes})
else:
obj = sqlhelper.Sqlhelper() # 实例化对象
name = request.POST.get('name')#获取老师姓名
#老师姓名插入到数据库中,并且获取这个老师的id
teacher_id = obj.create('insert into teachers(name) values(%s)', [name])
#获取所有班级id
class_ids = request.POST.getlist('class_id')
print(class_ids)#['1', '2', '3', '4']
#把老师id和班级id设计成 列表+元祖 的方式
lis = []
for cls_id in class_ids:
tup = (teacher_id,cls_id)
lis.append(tup)
print(lis)#[(4, '1'), (4, '2'), (4, '3'), (4, '4')]
#批量插入,因为全部插入完毕之后才提交一次,比下面的每一次插入就提交一次,速度要快很多。
obj.multiple_modify('insert into teacher_class(teacher_id,class_id) values(%s,%s)',lis)
obj.close()
return redirect('/teacher_class/')
#此方式是每插入一条数据,提交一次,会拖累操作数据库的速度
# for cls_id in class_ids:
# obj.modify('insert into teacher_class(teacher_id,class_id) values(%s,%s)', [teacher_id,cls_id])
#编辑老师班级
@wapper
def edit_teacher_class(request):
if request.method == 'GET':
#获取编辑的当前行的老师id
nid = request.GET.get('nid')
obj = sqlhelper.Sqlhelper()
#从数据库获取编辑的当前行的老师id和姓名
teacher = obj.get_one('select id,name from teachers where id=%s',[nid])
#获取老师任教的班级
teacher_classes = obj.get_list('select teacher_id,class_id from teacher_class where teacher_id=%s',[nid])
print(teacher_classes)#[{'teacher_id':1,'class_id':2},{'teacher_id':1,'class_id':3}]
#把班级id放在列表里面
lis = []
for dic in teacher_classes:
lis.append(dic['class_id'])
print(lis)#[2,3]
#获取所有班级
classes = obj.get_list('select id,title from classes',[])
obj.close()
return render(request,'edit_teacher_class.html',
{'teacher':teacher,'lis':lis,'classes':classes})
else:
nid = request.GET.get('nid')#老师id
name = request.POST.get('name')#老师姓名
class_id = request.POST.getlist('class_id')#该老师任教的班级列表
obj = sqlhelper.Sqlhelper()
#修改老师姓名
obj.modify('update teachers set name=%s where id = %s',[name,nid])
# 先删除数据库该老师id以及任教的班级id
obj.modify('delete from teacher_class where teacher_id = %s',[nid])
#再插入
lis = []
for cls_id in class_id:
tup = (nid,cls_id)
lis.append(tup)
obj.multiple_modify('insert into teacher_class(teacher_id,class_id) values(%s,%s)',lis)
obj.close()
return redirect('/teacher_class/')
################################# teacher_class 模态框+ajax添加########################################
def add_md_t_c(request):
if request.method == 'GET':
#有些浏览器在第二次添加的时候不支持等待3秒的操作,火狐浏览器支持。
time.sleep(3)
obj = sqlhelper.Sqlhelper()
result = obj.get_list('select id,title from classes',[])
obj.close()
return HttpResponse(json.dumps(result))
else:
ret = {'status':True,'message':None}
try:
name = request.POST.get('name')
class_ids = request.POST.getlist('class_ids')#['1','2','3']
obj = sqlhelper.Sqlhelper()
teacher_id = obj.create('insert into teachers(name) values(%s)',[name])
lis = []
for i in class_ids:
tup = (teacher_id,i)
lis.append(tup)
obj.multiple_modify('insert into teacher_class(teacher_id,class_id) values(%s,%s)',lis)
obj.close()
except Exception as e:
ret['status'] = False
ret['message'] = str(e)
return HttpResponse(json.dumps(ret))
2.teacher_class.html
{% extends 'layout.html' %}<!--继承母版-->
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<!-- 使用最新版本IE渲染-->
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!-- 为了确保移动设备的触屏缩放,添加视口 viewport-->
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! -->
<title>Title</title>
{% block css %}<!--在母版中添加样式类-->
<style>
.hide {
display: none
}
.shadow {
background: rgba(0, 0, 0, 0.4);
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
.add_model {
background: white;
width: 300px;
height: 400px;
position: fixed;
top: 50%;
left: 50%;
margin-top: -200px;
margin-left: -150px;
}
.loading {
width: 32px;
height: 32px;
position: fixed;
top: 50%;
left: 50%;
margin-top: -16px;
margin-left: -16px;
}
</style>
{% endblock %}
</head>
<body>
{% block content %}<!--在母版中添加内容-->
<h1>老师班级表</h1>
<p><a href="/add_teacher_class/" class="btn btn-primary">添加</a>
<input type="button" value="模态框添加" id="add_md" class="btn btn-info">
</p>
<table class="table table-striped table-bordered table-hover">
<thead>
<tr>
<th>id</th>
<th>老师姓名</th>
<th>班级名称</th>
<th>操作</th>
</tr>
</thead>
<tbody>
{% for row in result %}
<tr>
<td>{{ row.id }}</td>
<td>{{ row.name }}</td>
<td>
{% for item in row.titles %}
<span style="border:1px red solid;padding:5px;display:inline-block">{{ item }}</span>
{% endfor %}
</td>
<td>
<a href="/edit_teacher_class/?nid={{ row.id }}" class="glyphicon glyphicon-pencil">编辑</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
<!--遮罩层-->
<div class="shadow hide"></div>
<!--模态框添加-->
<div class="add_model hide">
<h2>添加老师和班级</h2>
<p>老师姓名:
<input type="text" id="tname">
</p>
<p>班级名称:
<select id="class_ids" multiple size="10">
</select>
</p>
<p>
<input type="button" value="提交" id="add_send">
<a href="/teacher_class/">取消</a>
</p>
</div>
<!--页面加载-->
<div class="loading hide"><img src="../static/images/loader.gif"></div>
{% endblock %}
<!--在母版中添加js-->
{% block js %}
<script src="../static/jquery-3.4.1.min.js"></script>
<script>
//页面加载完成,启动function函数里面的方法,极大地提高web应用程序的响应速度
$(function () {
f1();
f2();
});
function f1() {
$('#add_md').on('click', function () {
//点模态框添加,弹出遮罩层和gif加载图片
$('.shadow,.loading').removeClass('hide');
//触发ajax向服务器发出GET请求,拿到班级表
$.ajax({
url: '/add_md_t_c/',
type: 'GET',
dataType: 'JSON',//把服务器返回的数据转为对象
//当服务器处理成功之后,返回数据
success: function (arg) {
console.log(arg);//[{'id':1,'title':'全栈一期'},{'id':2,'title':'全栈二期']}
//隐藏gif加载图片
$('.loading').addClass('hide');
//弹出添加老师和班级的模态框
$('.add_model').removeClass('hide');
//循环增加option标签,i是arg的索引,row是arg的值,也就是元素
$.each(arg, function (i, row) {
//创造DOM对象,也就是具体的标签
var option = document.createElement('option');
//设置(增加)文本
$(option).text(row.title);
//设置(增加)属性
$(option).attr('value', row.id);
//select标签增加option标签
$('#class_ids').append(option);
})
}
})
})
}
function f2() {
$('#add_send').on('click', function () {
var name = $('#tname').val();
var class_ids = $('#class_ids').val();//['1','2','3']
$.ajax({
url: '/add_md_t_c/',
type: 'POST',
data: {'name': name, 'class_ids': class_ids},
traditional: true,//data有列表,需要设置此属性
dataType: 'JSON',//注意js是驼峰体,不然下面只能走else代码
success: function (arg) {
if (arg.status) {
location.reload()
} else {
alert(arg.message)
}
}
})
})
}
</script>
{% endblock %}
</body>
</html>
from django.contrib import admin
from django.urls import path
from app01 import views
urlpatterns = [
path('admin/', admin.site.urls),
path('students/', views.students),
path('add_student/', views.add_student),
path('del_student/', views.del_student),
path('edit_student/', views.edit_student),
path('add_model/', views.add_model),
path('del_model/', views.del_model),
path('edit_model/', views.edit_model),
path('teacher_class/', views.teacher_class),
path('add_teacher_class/', views.add_teacher_class),
path('edit_teacher_class/', views.edit_teacher_class),
path('add_md_t_c/', views.add_md_t_c),
path('login/', views.login),
]