在 之前 的一篇中通过普通的方式实现了教师表的增删改查。由于教师表与班级表之间存在多对对的关系,因此在原来的基础上做了一些修改:
- 通过访问
localhost:8080/teachers/
查看教师信息时,增加教师授课班级的显示 - 添加教师时,支持多选【可以get到在Django中如何获取多个值】
- 封装了一个SqlHelper类,通过对象的方式实现数据库的操作
- 实现了对话框式的添加【ajax的使用】
后期继续完善对话框式的编辑以及通过ajax实现的删除
urls.py增加:
path('get_all_class/', views.get_all_class),
path('modal_add_teacher/', views.modal_add_teacher),
views.py增加:
def get_all_class(request):
import time
time.sleep(3) # 等待时间会出现加载界面
obj = sqlHelper.SqlHelper()
class_list = obj.get_list("select * from class", [])
obj.close()
return HttpResponse(json.dumps(class_list))
def modal_add_teacher(request):
ret = {'status': True, 'message': None}
try:
name = request.POST.get('name')
class_id_list = request.POST.getlist('class_id_list')
obj = sqlHelper.SqlHelper()
last_id = obj.create("insert into teacher(name) values(%s)", [name, ])
data_list = []
for item in class_id_list:
temp = (last_id, item)
data_list.append(temp)
obj.multiple_modify("insert into teacher2class(teacher_id, class_id) values(%s, %s)", data_list)
obj.close()
except Exception as e:
ret['status'] = False
ret['message'] = str(e)
return HttpResponse(json.dumps(ret))
views.py修改:
def teachers(request):
teacher_list = sqlHelper.get_list("""
select teacher.id as tid,teacher.name,class.title from teacher
left join teacher2class on teacher.id=teacher2class.teacher_id
left join class on class.id=teacher2class.class_id
""", [])
result = {}
for teacher_item in teacher_list:
tid = teacher_item['tid']
if tid in result:
result[tid]['titles'].append(teacher_item['title'])
else:
result[tid] = {'tid': teacher_item['tid'],
'name': teacher_item['name'],
'titles': [teacher_item['title'], ]}
return render(request, 'teachers.html', {'teacher_list': result.values()})
def edit_teacher(request):
if request.method == 'GET':
teacher_id = request.GET.get('tid')
obj = sqlHelper.SqlHelper()
# 当前老师信息
teacher_info = obj.get_one("select * from teacher where id=%s", [teacher_id])
# 老师任教班级id [{'class_id':..},{'class_id':..}]
class_id_list = obj.get_list("select class_id from teacher2class where teacher_id=%s", [teacher_id])
temp = []
for item in class_id_list:
temp.append(item['class_id'])
# 班级列表
class_list = obj.get_list("select * from class", [])
obj.close()
return render(request, 'edit_teacher.html', {'teacher_info': teacher_info,
'class_id_list': temp,
'class_list': class_list})
else:
teacher_id = request.POST.get('id')
teacher_name = request.POST.get('name')
class_ids = request.POST.getlist('class_ids')
data_list = []
for class_id in class_ids:
temp = (teacher_id, class_id)
data_list.append(temp)
obj = sqlHelper.SqlHelper()
obj.modify("update teacher set name=%s where id=%s",
[teacher_name, teacher_id])
obj.modify("delete from teacher2class where teacher_id=%s", [teacher_id])
obj.multiple_modify("insert into teacher2class(teacher_id,class_id) "
"values(%s, %s)", data_list)
obj.close()
return redirect('/teachers/')
teachers.tml
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>教师列表</title>
<style type="text/css">
.hide{display: none;}
.shadow{
position: fixed;
left:0;
right: 0;
top: 0;
bottom: 0;
background-color: rgba(0,0,0,0.4);
z-index: 9999;
}
.loading{
position: fixed;
width:260px;
height:400px;
top:50%;
left: 50%;
margin-left:-130px;
margin-top:-200px;
background-image:url("/static/images/loading.gif");
}
.modal{
z-index: 10000;
position: fixed;
left: 50%;
top: 50%;
width: 400px;
height: 300px;
background-color: #fff;
margin-left: -200px;
margin-top: -150px;
}
</style>
</head>
<body>
<h1>教师列表</h1>
<div>
<a href="/add_teacher/">添加教师</a>
|
<a id="btnAdd">对话框添加教师</a>
</div>
<table border="1">
<thead>
<tr>
<th>教师ID</th>
<th>教师名称</th>
<th>任教班级名称</th>
<th>操作</th>
</tr>
</thead>
<tbody>
{% for teacher_item in teacher_list %}
<tr>
<td>{{ teacher_item.tid }}</td>
<td>{{ teacher_item.name }}</td>
<td>
{% for title in teacher_item.titles %}
<span>{{ title }}</span>
{% endfor %}
</td>
<td>
<a href="/edit_teacher/?tid={{ teacher_item.tid }}">编辑</a>|
<a href="/del_teacher/?tid={{ teacher_item.tid }}">删除</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
<div id="shadow" class="shadow hide"></div>
<div id="loading" class="loading hide"></div>
<div id="add-modal" class="modal hide">
<h1>添加教师</h1>
教师名称:<input type="text" id="teacher_name" name="teacher_name"/><br/>
任教班级:
<select name="" id="classIds" multiple size="5"></select>
<a id="addSubmit">提交</a>
</div>
<script type="text/javascript" src="/static/js/jquery-1.12.0.min.js"></script>
<script type="text/javascript">
$(function(){
bindAdd();
bindAddSubmit();
});
function bindAdd(){
$("#btnAdd").click(function () {
$("#shadow,#loading").removeClass('hide');
/**
* 1.发送ajax请求,获取所有的班级信息
* 2.在select下生成所有的option
*/
$.ajax({
url:'/get_all_class/',
type:'post',
dataType:'JSON',
success:function(data){
console.log(data);
//将所有数据添加到select,option
$.each(data, function (i, row) {
let tag = document.createElement('option');
tag.innerHTML = row.title;
tag.setAttribute('value', row.id);
$("#classIds").append(tag);
});
$("#loading").addClass('hide');
$("#add-modal").removeClass("hide");
}
})
})
}
function bindAddSubmit(){
$("#addSubmit").click(function(){
let name = $("#teacher_name").val();
let class_id_list = $("#classIds").val();
$.ajax({
url:'/modal_add_teacher/',
type:'post',
data:{'name':name, 'class_id_list': class_id_list},
traditional:true,//如果提交的数据有列表,则需要添加此属性
dataType:'JSON',
success:function(data){
if(data.status){
location.reload();
}else{
alert(data.message);
}
}
})
});
}
</script>
</body>
</html>