此篇为代码流程的注释以及自己写的小项目的思路:

首先是项目的路由配置:

 urlpatterns = [
# url(r'^admin/', admin.site.urls),
url(r'^yemian/',yemian),
url(r'^zuoye/',zuoye),
url(r'^class/',views.class_list),
url(r'^class_add/',views.class_add),
url(r'^class_delete/',views.class_delete),
url(r'^class_edit/',views.class_edit),
url(r'^teacher/',tvi.teacher),
url(r'^tadd/',tvi.t_add),
url(r'^tedit/',tvi.t_edit),
url(r'^tdelete/',tvi.t_delete),
url(r'^student/',svi.student),
url(r'^sadd/',svi.s_add),
url(r'^sedit/',svi.s_edit),
url(r'^sdelete/',svi.s_delete),
url(r'^modal_add_student/', svi.modal_add_student),
url(r'^modal_add_teacher/', tvi.modal_add_teacher), url(r'^modal_add_class/', modal_add_class), url(r'^edit_modal_class/', views.edit_modal_add_class),
url(r'^modal_edit_student/', svi.modal_edit_student), url(r'^modal_delete_student/', svi.modal_delete_student), url(r'^modal_edit_teacher/', tvi.modal_edit_teacher),
url(r'^modal_delete_teacher/', tvi.modal_delete_teacher), ]

项目路由

路由的配置很重要,关乎于前端与后端的交互通道,路由的前面用正则匹配页面信息GET后的地址,然后进行后端函数的调用

<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<link rel="stylesheet" href="/static/dist/css/bootstrap.css">
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js "></script>
<script src="/static/dist/js/bootstrap.js"></script>
<title>Title</title>
<style>
body {
background-color: black;
} .ya {
background-color: white;
/*border-radius: 2%;*/
width: 450px;
height: 250px;
margin-top: 200px;
margin-left: 30%;;
position: fixed;
} .btn-inf {
color: white;
background-color: black;
border: black;
}
.btn-inf:active{
color: white !important;
background-color: #222222 !important;
border: black !important;
}
.btn-inf:link {
color: white;
background-color: black;
border: black;
} .btn-inf:hover {
color: white;
background-color: #333333;
}
.glyphicon {
margin-right: 10px;
}
.yu{
background-color:black ;
color:white ;
}
.nuo{
margin-top: 40px;
margin-left:10px ;
}
.btn-sc{
color: black;
background-color: white;
border: white;
/*width: 300px;*/
/*height: 100px;*/
/*font-size: 50px;*/
padding: 10px;
position: fixed;
top:40%;
left: 40%;
}
.btn-sc:hover{
color:white ;
background-color: #5e5e5e;
border: white;
}
.btn-lg{
padding: 20px 32px;
font-size: 36px;
line-height: 2;
border-radius: 12px;
}
</style>
</head>
<body>
<div class="container ya img-rounded hidden">
<form class="form-horizontal nuo novalidate" action="/zuoye/" method="post">
<div class="form-group" id="in1">
<label for="inputEmail3" class="col-sm-2 control-label">用户名</label> <div class="input-group col-sm-8">
<span class="glyphicon glyphicon-user input-group-addon yu"></span>
<input type="text" class="form-control" id="inputEmail3" placeholder="用户名"
aria-describedby="inputEmail3" name="username">
<span class="glyphicon glyphicon-ok form-control-feedback hidden" id="namer"></span>
<span class="glyphicon glyphicon-warning-sign form-control-feedback hidden"
id="namew"></span>
<span class="glyphicon glyphicon-remove form-control-feedback hidden" id="namec"></span>
</div>
</div>
<div class="form-group" id="in2">
<label for="inputPassword3" class="col-sm-2 control-label">密码</label>
<div class="input-group col-sm-8">
<span class="glyphicon glyphicon-lock input-group-addon yu"></span>
<input type="password" class="form-control" id="inputPassword3" placeholder="密码" name="password">
<span class="glyphicon glyphicon-ok form-control-feedback hidden" id="pwdr"></span>
<span class="glyphicon glyphicon-warning-sign form-control-feedback hidden"
id="pwdw"></span>
<span class="glyphicon glyphicon-remove form-control-feedback hidden" id="pwdc"></span>
</div>
</div> <div class="form-group">
<div class="col-sm-offset-2 col-sm-8">
<input type="submit" class="btn btn-inf btn-block" id="bu" value="登录">
</div>
</div>
<div>
<h3 style="text-align: center">{{ error_msg }}</h3>
</div>
</form>
</div>
<div class="tubiao">
<a href="javascript:void(0)" class="glyphicon glyphicon-tasks btn btn-sc btn-lg"> Login</a> </div> <script>
$("#inputEmail3").on("blur",function () {
zhi=$("#inputEmail3").val();
if (zhi.length==0){
$("#namew").removeClass("hidden");
$("#in1").addClass("has-warning")
}
if (zhi.length>15||(zhi.length<6&&zhi.length!=0)){
$("#namec").removeClass("hidden");
$("#in1").addClass("has-error")
}
if(zhi.length>=6&&zhi.length<15){
$("#namer").removeClass("hidden");
$("#in1").addClass("has-success")
} });
$("#inputEmail3").on("focus",function () {
$("#in1").removeClass("has-error");
$("#in1").removeClass("has-success");
$("#in1").removeClass("has-warning");
$("#namew").addClass("hidden");
$("#namec").addClass("hidden");
$("#namer").addClass("hidden");
});
$("#inputPassword3").on("blur",function () {
pwd=$("#inputPassword3").val();
if (pwd.length==0){
$("#pwdw").removeClass("hidden");
$("#in2").addClass("has-warning")
}
if (pwd.length>15||(pwd.length<6&&pwd.length!=0)){
$("#pwdc").removeClass("hidden");
$("#in2").addClass("has-error")
}
if(pwd.length>=6&&pwd.length<15) {
$("#pwdr").removeClass("hidden");
$("#in2").addClass("has-success")
} });
$("#inputPassword3").on("focus",function () {
$("#in2").removeClass("has-error");
$("#in2").removeClass("has-success");
$("#in2").removeClass("has-warning");
$("#pwdw").addClass("hidden");
$("#pwdc").addClass("hidden");
$("#pwdr").addClass("hidden");
});
$(".btn-sc").on("click",function () {
$(".btn-sc").addClass("hidden");
$(".ya").removeClass("hidden"); })
</script>
</body>
</html>

登录页面的html

登录页面的代码较简单,通过form表单的提交,将账号密码提交到后端进行判断,判断正确跳转网页,判断失败就提升错误信息,下面是相关的函数代码:

 def zuoye(request):
global i
i=i+1
if request.method == "GET":
return render(request, "zuoye.html")
else:
if request.POST.get("username") == "gaoshengyue" and request.POST.get("password") == "gsy121994":
# 登陆成功
return redirect("/class/")
else:
if i>2:
return render(request, "zuoye.html", {"error_msg": "输入错误"})
else:
return render(request, "zuoye.html")

登录跳转后端py

函数中先进行判断,如果是get请求就开始用render渲染页面,render第一个是传的参数request,第二个是要渲染的页面,第三个是要返回给页面的值,也就是我们模板语言要通过

{{}}来取到的值,用字典的形式传。

用.POST.get来取值,传值的时候表单中的input有name所以字典的key就是这些name,对应的值就是传的值,然后进行判断,登录成功的话跳转到主页面class_list,用redirect来跳转

主页面class_listhtm代码如下:

 <!DOCTYPE html>
<html lang="zh-CN"><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="/static/dist/css/bootstrap.css">
<!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! -->
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="http://v3.bootcss.com/favicon.ico">
<title>Dashboard Template for Bootstrap</title> <!-- Bootstrap core CSS -->
<link href="/static/Dashboard%20Temp_files/bootstrap.css" rel="stylesheet"> <!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<link href="/static/Dashboard%20Temp_files/ie10-viewport-bug-workaround.css" rel="stylesheet"> <!-- Custom styles for this template -->
<link href="/static/Dashboard%20Temp_files/dashboard.css" rel="stylesheet"> <!-- Just for debugging purposes. Don't actually copy these 2 lines! -->
<!--[if lt IE 9]><script src="../../assets/js/ie8-responsive-file-warning.js"></script><![endif]-->
<script src="/static/Dashboard%20Temp_files/ie-emulation-modes-warning.js"></script> <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://cdn.bootcss.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://cdn.bootcss.com/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<style>
.col-centered {
float: none;
margin: 0 auto;
}
.cd{
background-color: black;
}
</style>
<body> <nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Project name</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-right">
<li><a href="#">Dashboard</a></li>
<li><a href="#">Settings</a></li>
<li><a href="#">Profile</a></li>
<li><a href="#">Help</a></li>
</ul>
<form class="navbar-form navbar-right">
<input class="form-control" placeholder="Search..." type="text">
</form>
</div>
</div>
</nav> <div class="container-fluid">
<div class="row">
<div class="col-sm-3 col-md-2 sidebar"> <div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true">
<div class="panel panel-default">
<div class="panel-heading cd" role="tab" id="headingOne">
<h4 class="panel-title">
<a data-toggle="collapse" href="/class/" id="classfl">
班级
</a>
</h4>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading" role="tab" id="headingTwo">
<h4 class="panel-title">
<a class="collapsed" href="/teacher/" >
教师
</a>
</h4>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading" role="tab" id="headingThree">
<h4 class="panel-title">
<a class="collapsed" href="/student/" aria-controls="collapseThree">
学生
</a>
</h4>
</div>
</div>
</div> </div>
<div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main"> <div class="panel panel-default">
<div class="panel-heading">Panel heading</div>
<div class="panel-body">
<div class="row">
<form class="navbar-form navbar-left col-sm-12" role="search">
<div class="form-group">
<input type="text" class="form-control" placeholder="搜索">
</div>
<button type="submit" class="btn btn-info">搜索</button> </form>
<a href="/class_add/" class="btn btn-success pull-right" style="margin-right: 15px;margin-top:8px ">网页添加</a>
<button type="submit" class="btn btn-success pull-right" style="margin-right: 15px;margin-top:8px " data-toggle="modal" data-target="#myModal">添加</button>
</div>
<div class="modal fade j" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog j" role="document">
<div class="modal-content j">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
<h4 class="modal-title" id="myModalLabel">信息填写</h4>
</div>
<div class="modal-body">
<form method="post">
<div class="form-group">
<label for="d1">姓名</label>
<input type="text" class="hui form-control" id="d1">
<span id="error-msg"></span>
<div class="modal-footer">
<button class="an btn btn-default" data-dismiss="modal" >Close</button>
<button id="modal-submitt" class="anq btn btn-primary" type="button" >提交</button>
</div>
</div>
</form>
</div> </div>
</div>
</div> {# <edit_modal>#}
<div class="modal fade j" id="edit_myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog j" role="document">
<div class="modal-content j">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
<h4 class="modal-title" id="myModalLabel">信息填写</h4>
</div>
<div class="modal-body">
<form> <div class="form-group">
<input type="text" style="display: none" id="ed2">
<label for="ed1">班级名</label>
<input type="text" class="hui form-control" id="ed1">
<span id="edit_error-msg"></span>
<div class="modal-footer">
<button class="an btn btn-default" data-dismiss="modal" >Close</button>
<button id="edit_modal-submitt" class="anq btn btn-primary" type="button" >提交</button>
</div>
</div>
</form>
</div> </div>
</div>
</div>
{# </edit_modal>#}
<div class="table-responsive">
<table class="table table-striped table-bordered">
<thead>
<tr>
<th class="col-sm-1">#</th>
<th>班级名</th>
<th>操作</th>
</tr>
</thead>
<tbody>
{% for class in class_list %}
<tr>
<td class="col-sm-1">{{ class.cid}}</td>
<td>{{ class.cname }}</td>
<td class="col-sm-6 ">
<a href="/class_delete/?class_id={{ class.cid }}" class="del btn btn-danger col-sm-offset-3 glyphicon glyphicon-remove">删除</a>
<a href="/class_edit/?class_id={{ class.cid }}" class="w btn btn-success glyphicon glyphicon-pencil">编辑</a>
<button class="wm btn btn-success glyphicon glyphicon-pencil">modal编辑</button>
</td> </tr>
{% endfor %}
</tbody>
</table>
</div> <nav aria-label="Page navigation" class=" pull-right">
<ul class="pagination">
<li>
<a href="#" aria-label="Previous">
<span aria-hidden="true">&laquo;</span>
</a>
</li>
<li><a href="#">1</a></li>
<li><a href="#">2</a></li>
<li><a href="#">3</a></li>
<li><a href="#">4</a></li>
<li><a href="#">5</a></li>
<li>
<a href="#" aria-label="Next">
<span aria-hidden="true">&raquo;</span>
</a>
</li>
</ul>
</nav>
</div>
</div>
</div>
</div>
</div> <!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="/static/Dashboard%20Temp_files/jquery.js"></script>
<script>window.jQuery || document.write('<script src="../../assets/js/vendor/jquery.min.js"><\/script>')</script>
<script src="/static/Dashboard%20Temp_files/bootstrap.js"></script>
<!-- Just to make our placeholder images work. Don't actually copy the next line! -->
<script src="/static/Dashboard%20Temp_files/holder.js"></script>
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<script src="/static/Dashboard%20Temp_files/ie10-viewport-bug-workaround.js"></script> <script> $("#modal-submitt").on("click", function () {
{# $("#myModal form").submit();#}
var className = $("#d1").val();
console.log(className);
{# 用AJAX不刷新页面提交到后端#}
$.ajax({
url: "/modal_add_class/",
type: "post",
data: {"classname": className},
success: function (data) {
if (data === "OK"){
{# if (data.length != 0) {#}
{# var clasData = JSON.parse(data);#}
{# var newTr = document.createElement("tr");#}
{# $(newTr).append("<td>" + clasData["id"] + "</td>");#}
{# $(newTr).append("<td>" + clasData["name"] + "</td>");#}
{# $("td:last").clone().appendTo($(newTr));#}
{# $(newTr).appendTo("tbody");#}
location.href="/class/";
}else {
$("#error-msg").text(data).parent().parent().addClass("has-error");
}
}
})
}); $(".wm").on("click", function () {
$tdz=$(this).parent().parent().children();
ce_id=$($tdz[0]).text();
ce_name=$($tdz[1]).text();
$("#edit_myModal").modal("show");
$("#ed2").val(ce_id);
$("#ed1").val(ce_name);
{# .find("#ed1").val(ce_name)#}
});
$("#edit_modal-submitt").on("click",function () {
var class_d=$("#ed2").val();
var class_n=$("#ed1").val();
$.ajax({
url:"/edit_modal_class/",
type:"post",
data:{"class_d":class_d,"class_n":class_n},
success:function (data) {
if (data==='OK'){
location.reload()
}
else {
$("#edit_error-msg").text(data).parent().parent().addClass("has-error");
}
}
})
}) </script>
</body></html>

主页面班级管理html

主页面的渲染上,内容展示的部分,用到了模板语言,循环将后端从数据库拿出来的数据进行展示,同时添加的话通过给添加按钮绑定时间,触发模态框,然后再给modal的sumbit按钮绑定获取值并且提交给后端的事件,通过ajax来向后端发送数据。

这里要详细说一下ajax部分:

$.ajax({
url: "/modal_add_class/",                                             //这里是跳转的url,通过后端路由,调用modal添加数据的函数
type: "post",                                                                  //传送给后端的命令属性
data: {"classname": className},                              //ajax传给后端的值,字典形式,不能穿列表如果要列表的话要先json.stringify来转换成字符串,后端再通过json.loads来转换
success: function (data) {
if (data === "OK"){                                                     //data为后端return会前端的值,后端一般会使用HttpResponse来返回,也可以是字典。

location.href="/class/";                                            //跳转的页面也可以location.reload()来直接跳转回本页面
}else {
$("#error-msg").text(data).parent().parent().addClass("has-error");                       //这里是添加错误信息,has-error是bootstrap中错误信息的样式
}
}
})

取值的话还是在主页面通过jQuery选择器来取值,下面贴的是后端再班级管理页面的代码:

 def student(request):

    conn=pymysql.connect(
host='127.0.0.1',port=3306,
user='root',password='',db='day66',charset='utf8' )
cursor=conn.cursor(cursor=pymysql.cursors.DictCursor)
cursor.execute("select student.id,student.sname,class.cname,student.class_id from student INNER JOIN class on student.class_id = class.cid")
student_list=cursor.fetchall()
cursor.execute("select cid,cname from class")
cs_list = cursor.fetchall()
cursor.close()
conn.close()
return render(request,'student.html',{'student_list':student_list,"cs_list":cs_list})

主页面渲染

通过连接数据库,然后通过sql语句来获取数据库中的班级信息值,然后传给前端,前端再通过模板语言来进行展示

 def modal_add_class(request):
print(request.method)
if request.method == "POST":
print()
new_class_name = request.POST.get("classname")
if new_class_name:
conn = pymysql.connect(
host='127.0.0.1', port=3306,
user='root', password='', db='day66', charset='utf8'
)
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
cursor.execute("insert into class(cname) VALUES (%s)", [new_class_name,])
conn.commit()
cursor.close()
conn.close()
return HttpResponse("OK")
else:
error = "班级名称不能为空"
return HttpResponse(error)

主页面添加班级信息

这部分函数通过ajax传过来的值,用.POST.get(字典的ey)的方式获取,然后用sql语句insert into后端的数据库中,然后返回前端OK,前端判断接受回的消息是OK,就刷新页面,这样主页面再次回到渲染函数,渲染出来的就是包括新添加数据的页面了。

接下来是班级信息的编辑:

 def edit_modal_add_class(request):
if request.method == "POST":
new_class_d = request.POST.get("class_d")
new_class_n = request.POST.get("class_n")
if new_class_n:
conn = pymysql.connect(
host='127.0.0.1', port=3306,
user='root', password='', db='day66', charset='utf8'
)
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
cursor.execute("update class set cname=%s where cid=%s ", [new_class_n,new_class_d ])
conn.commit()
cursor.close()
conn.close()
return HttpResponse("OK")
else:
error = "班级名称不能为空"
return HttpResponse(error)

主页面编辑班级信息

这部分函数,同样是接受ajax传来的值,然后用sql语句的update来进行数据的更新

下面是学生信息部分的添加、编辑、与删除。

 <!DOCTYPE html>
<html lang="zh-CN"><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="/static/dist/css/bootstrap.css">
<!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! -->
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="http://v3.bootcss.com/favicon.ico">
<title>Dashboard Template for Bootstrap</title> <!-- Bootstrap core CSS -->
<link href="/static/Dashboard%20Temp_files/bootstrap.css" rel="stylesheet"> <!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<link href="/static/Dashboard%20Temp_files/ie10-viewport-bug-workaround.css" rel="stylesheet">
<link href="/static/sweetalert/sweetalert.css" rel="stylesheet"> <!-- Custom styles for this template -->
<link href="/static/Dashboard%20Temp_files/dashboard.css" rel="stylesheet"> <!-- Just for debugging purposes. Don't actually copy these 2 lines! -->
<!--[if lt IE 9]><script src="../../assets/js/ie8-responsive-file-warning.js"></script><![endif]-->
<script src="/static/Dashboard%20Temp_files/ie-emulation-modes-warning.js"></script> <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://cdn.bootcss.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://cdn.bootcss.com/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<style>
.col-centered {
float: none;
margin: 0 auto;
}
.cd{
background-color: black;
}
</style>
<body> <nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Project name</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-right">
<li><a href="#">Dashboard</a></li>
<li><a href="#">Settings</a></li>
<li><a href="#">Profile</a></li>
<li><a href="#">Help</a></li>
</ul>
<form class="navbar-form navbar-right">
<input class="form-control" placeholder="Search..." type="text">
</form>
</div>
</div>
</nav> <div class="container-fluid">
<div class="row">
<div class="col-sm-3 col-md-2 sidebar"> <div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true">
<div class="panel panel-default">
<div class="panel-heading cd" role="tab" id="headingOne">
<h4 class="panel-title">
<a href="/class/" id="classfl">
班级
</a>
</h4>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading" role="tab" id="headingTwo">
<h4 class="panel-title">
<a class="collapsed" href="/teacher/" aria-controls="collapseTwo">
教师
</a>
</h4>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading" role="tab" id="headingThree">
<h4 class="panel-title">
<a class="collapsed" href="/student/" aria-controls="collapseThree">
学生
</a>
</h4>
</div>
</div>
</div> </div>
<div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main"> <div class="panel panel-default">
<div class="panel-heading">Panel heading</div>
<div class="panel-body">
<div class="row">
<form class="navbar-form navbar-left col-sm-12" role="search">
<div class="form-group">
<input type="text" class="form-control" placeholder="搜索">
</div>
<button type="submit" class="btn btn-info">搜索</button> </form>
<a href="/sadd/" class="btn btn-success pull-right" style="margin-right: 15px;margin-top:8px ">网页添加</a>
<button class="btn btn-success pull-right" style="margin-right: 15px;margin-top:8px " data-toggle="modal" data-target="#myModal">添加</button>
</div>
<div class="modal fade j" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog j" role="document">
<div class="modal-content j">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
<h4 class="modal-title" id="myModalLabel">信息填写</h4>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label for="d1">学生名</label>
<input type="text" class="hui form-control" id="d1">
</div>
<div class="form-group">
<label for="d3" class=" control-label">班级id</label>
<select class="form-control" name="sclass">
{% for csl in cs_list %}
<option value="{{ csl.cid }}">{{ csl.cname }}</option>
{% endfor %}
</select>
</div>
<span id="error-msg"></span>
<div class="modal-footer">
<button class="an btn btn-default" data-dismiss="modal">Close</button>
<button class="anq btn btn-primary" id="modal-submit" type="button" >确定添加</button>
</div>
</form>
</div> </div>
</div>
</div> {# <modaladd>#}
<div class="modal fade j" id="edit_myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog j" role="document">
<div class="modal-content j">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
<h4 class="modal-title" id="myModalLabel">信息填写</h4>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<input type="text" style="display: none" id="ed3">
<label for="d1">学生名</label>
<input type="text" class="hui form-control" id="ed1">
</div>
<div class="form-group">
<label for="edit_sele" class=" control-label">班级id</label>
<select class="form-control" id="edit_sele">
{% for csl in cs_list %}
<option value="{{ csl.cid }}">{{ csl.cname }}</option>
{% endfor %}
</select>
</div>
<span id="error-msg"></span>
<div class="modal-footer">
<button class="an btn btn-default" data-dismiss="modal">Close</button>
<button class="anq btn btn-primary" id="edit-modal-submit" type="button" >确定修改</button>
</div>
</form>
</div> </div>
</div>
</div> {# </modaladd>#} <div class="table-responsive">
<table class="table table-striped table-bordered">
<thead>
<tr>
<th class="col-sm-1">#</th>
<th>学生名</th>
<th>班级名</th>
<th>操作</th>
</tr>
</thead>
<tbody>
{% for student in student_list %}
<tr>
<td class="col-sm-1">{{ student.id}}</td>
<td>{{ student.sname }}</td>
<td cid="{{ student.class_id }}">{{ student.cname }}</td>
<td class="col-sm-8 ">
<a href="/sdelete/?s_id={{ student.id }}" class="del btn btn-danger col-sm-offset-3 glyphicon glyphicon-remove">删除</a>
<a href="/sedit/?s_id={{ student.id }}" class="w btn btn-success glyphicon glyphicon-pencil">编辑</a>
<button class="wm btn btn-success glyphicon glyphicon-pencil">modal编辑</button>
<button id="sweetd" class="del btn btn-danger glyphicon glyphicon-remove">页面删除</button>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div> <nav aria-label="Page navigation" class=" pull-right">
<ul class="pagination">
<li>
<a href="#" aria-label="Previous">
<span aria-hidden="true">&laquo;</span>
</a>
</li>
<li><a href="#">1</a></li>
<li><a href="#">2</a></li>
<li><a href="#">3</a></li>
<li><a href="#">4</a></li>
<li><a href="#">5</a></li>
<li>
<a href="#" aria-label="Next">
<span aria-hidden="true">&raquo;</span>
</a>
</li>
</ul>
</nav>
</div>
</div>
</div>
</div>
</div> <!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="/static/Dashboard%20Temp_files/jquery.js"></script>
<script>window.jQuery || document.write('<script src="../../assets/js/vendor/jquery.min.js"><\/script>')</script>
<script src="/static/Dashboard%20Temp_files/bootstrap.js"></script>
<!-- Just to make our placeholder images work. Don't actually copy the next line! -->
<script src="/static/Dashboard%20Temp_files/holder.js"></script>
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<script src="/static/Dashboard%20Temp_files/ie10-viewport-bug-workaround.js"></script>
<script src="/static/sweetalert/sweetalert.min.js"></script>
<script>
$("#modal-submit").on("click", function () {
{# $("#myModal form").submit();#}
var studentName = $("#d1").val();
var studentId=$("option:selected").val();
{# 用AJAX不刷新页面提交到后端#}
$.ajax({
url: "/modal_add_student/",
type: "POST",
data: {"studentname": studentName,"studentid":studentId},
success: function (data) {
if (data === "OK"){
location.href="/student/"; }else {
$("#error-msg").text(data).parent().parent().addClass("has-error");
}
}
})
});
$(".wm").on("click",function () {
$sz=$(this).parent().parent().children();
$("#ed1").val($($sz[1]).text());
zhi=$($sz[2]).attr("cid");
$("#edit_sele").val(zhi);
$("#ed3").val($($sz[0]).text());
$("#edit_myModal").modal("show");
});
$("#edit-modal-submit").on("click", function () {
var studentName = $("#ed1").val();
var studentId=$("#edit_sele option:selected").val();
var student_gd=$("#ed3").val();
{# 用AJAX不刷新页面提交到后端#}
$.ajax({
url: "/modal_edit_student/",
type: "POST", data: {"studentname": studentName,"studentid":studentId,"student_gd":student_gd},
success: function (data) {
if (data === "OK"){
location.href="/student/"; }else {
$("#error-msg").text(data).parent().parent().addClass("has-error");
}
}
})
}); {# 二次删除 #}
$("table").on("click" , "#sweetd", function () {
var studentID = $(this).parent().parent().children().eq(0).text();
var $tr = $(this).parent().parent();
// 弹出sweetalert二次确认框
// swal("", "", "warning");
swal({
title: "删除此学生信息?",
text: "删除后无法回复。",
type: "warning",
showCancelButton: true,
closeOnConfirm: false,
confirmButtonText: "继续删除!",
confirmButtonColor: "#ec6c62",
cancelButtonText: "再想一想"
}, function (isConfirm) {
if (!isConfirm) return;
$.ajax({
type: "post",
url: "/modal_delete_student/",
data: {"student_id": studentID},
success: function (data) {
var dataObj = $.parseJSON(data);
if (dataObj.status === 0) { //后端删除成功
swal("删除成功", dataObj.msg, "success");
$tr.remove() //删除页面中那一行数据
} else {
swal("出错啦。。。", dataObj.msg, "error"); //后端删除失败
}
},
error: function () { // ajax请求失败
swal("啊哦。。。", "服务器走丢了。。。", "error");
}
})
});
})
</script>
</body></html>

学生信息管理html

学生信息页面的js中,值得一提的是学生的班级信息,并不是通过input中type为text的输入框来获取值了,而是通过select标签来进行选择性的value获取,展示的时候同样是通过模板语言的循环将数据展示,select也是如此。

在学生添加的过程中,select标签要通过option:selected 来判断是否为选中项,获取value的方法同输入框。

而且这时要考虑到学生编辑时展示的信息时学生当前最新信息,所以要在input框中添加学生当前最新姓名,还有所属班级。那样的话都input输入框可以用jQuery中的.val()方法来传入当前值,也就是获取所点击编辑的父代的父代的学生名字的td标签的text值,然后赋给当前modal输入框的value属性,select选中的话也是.val()方法,不过val()的括号中要添加的就是班级的id的值了,这样的话值与select标签中option标签的value相等就会选中了。

在删除学生信息的时候,用了二次提醒删除事件,导入了一个插件sweetalert也就是弹出是否确定删除的信息,详细方法参考sweetalert的官网使用。

 def student(request):

    conn=pymysql.connect(
host='127.0.0.1',port=3306,
user='root',password='',db='day66',charset='utf8' )
cursor=conn.cursor(cursor=pymysql.cursors.DictCursor)
cursor.execute("select student.id,student.sname,class.cname,student.class_id from student INNER JOIN class on student.class_id = class.cid")
student_list=cursor.fetchall()
cursor.execute("select cid,cname from class")
cs_list = cursor.fetchall()
cursor.close()
conn.close()
return render(request,'student.html',{'student_list':student_list,"cs_list":cs_list})

学生信息展示

同样通过查找数据库的数据来进行数据展示

 def modal_add_student(request):
if request.method == "POST":
new_student_name = request.POST.get("studentname")
new_student_id_=request.POST.get("studentid")
new_student_id_=int(new_student_id_)
conn = pymysql.connect(
host='127.0.0.1', port=3306,
user='root', password='', db='day66', charset='utf8'
)
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
if new_student_name:
cursor.execute("insert into student(sname,class_id)values (%s,%s)", [new_student_name,new_student_id_])
conn.commit()
cursor.close()
conn.close()
return HttpResponse("OK") else:
error = "班级名称不能为空"
return HttpResponse(error)

学生信息添加

同班级信息添加,不过这时要添加的就是两条信息了,所以表的自增ID不用添加。

 def modal_edit_student(request):
if request.method == "POST":
new_student_name = request.POST.get("studentname")
new_student_id_=request.POST.get("studentid")
new_student_gd = request.POST.get("student_gd")
new_student_id=int(new_student_id_)
new_student_gd_ = int(new_student_gd)
conn = pymysql.connect(
host='127.0.0.1', port=3306,
user='root', password='', db='day66', charset='utf8'
)
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
if new_student_name:
cursor.execute("update student set sname=%s where id=%s ", [new_student_name,new_student_gd])
cursor.execute("update student set class_id=%s where id=%s ", [new_student_id, new_student_gd])
conn.commit()
cursor.close()
conn.close()
return HttpResponse("OK") else:
error = "学生名称不能为空"
return HttpResponse(error)

学生信息编辑

同班级信息编辑差不多,不过修改的时候要带上class_id

 def modal_delete_student(request):
if request.method == "POST":
new_student_gd = request.POST.get("student_id")
new_student_id=int(new_student_gd)
print(new_student_id)
conn = pymysql.connect(
host='127.0.0.1', port=3306,
user='root', password='', db='day66', charset='utf8'
)
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
if new_student_gd:
cursor.execute("delete from student where id=%s ", [new_student_id])
conn.commit()
cursor.close()
conn.close()
ret=json.dumps({"status":0,"msg":'一鼓作气'})
return HttpResponse(ret)
else:
error = "有一些小毛病"
ret = json.dumps({"status": 1, "msg": error})
return HttpResponse(ret)

学生信息删除

返回给前端的是一条字典信息,前面status中是状态码,后面的msg中是错误信息,前端通过状态码来判断是否修改完成。因为前后端间传值只能是字符串所以要用json.dumps来序列化一下,前端通过JSON.parse来解析。

下面是比较复杂的教师页面管理:

 <!DOCTYPE html>
<html lang="zh-CN"><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="/static/dist/css/bootstrap.css">
<!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! -->
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="http://v3.bootcss.com/favicon.ico">
<title>Dashboard Template for Bootstrap</title> <!-- Bootstrap core CSS -->
<link href="/static/Dashboard%20Temp_files/bootstrap.css" rel="stylesheet"> <!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<link href="/static/Dashboard%20Temp_files/ie10-viewport-bug-workaround.css" rel="stylesheet"> <!-- Custom styles for this template -->
<link href="/static/Dashboard%20Temp_files/dashboard.css" rel="stylesheet"> <!-- Just for debugging purposes. Don't actually copy these 2 lines! -->
<!--[if lt IE 9]><script src="../../assets/js/ie8-responsive-file-warning.js"></script><![endif]-->
<script src="/static/Dashboard%20Temp_files/ie-emulation-modes-warning.js"></script>
<link href="/static/sweetalert/sweetalert.css" rel="stylesheet">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://cdn.bootcss.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://cdn.bootcss.com/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<style>
.col-centered {
float: none;
margin: 0 auto;
}
.cd{
background-color: black;
}
</style>
<body> <nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Project name</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-right">
<li><a href="#">Dashboard</a></li>
<li><a href="#">Settings</a></li>
<li><a href="#">Profile</a></li>
<li><a href="#">Help</a></li>
</ul>
<form class="navbar-form navbar-right">
<input class="form-control" placeholder="Search..." type="text">
</form>
</div>
</div>
</nav> <div class="container-fluid">
<div class="row">
<div class="col-sm-3 col-md-2 sidebar"> <div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true">
<div class="panel panel-default">
<div class="panel-heading cd" role="tab" id="headingOne">
<h4 class="panel-title">
<a href="/class/" id="classfl">
班级
</a>
</h4>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading" role="tab" id="headingTwo">
<h4 class="panel-title">
<a class="collapsed" href="/teacher/" aria-controls="collapseTwo">
教师
</a>
</h4>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading" role="tab" id="headingThree">
<h4 class="panel-title">
<a class="collapsed" href="/student/"aria-controls="collapseThree">
学生
</a>
</h4>
</div>
</div>
</div> </div>
<div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main"> <div class="panel panel-default">
<div class="panel-heading">Panel heading</div>
<div class="panel-body">
<div class="row">
<form class="navbar-form navbar-left col-sm-12" role="search">
<div class="form-group">
<input type="text" class="form-control" placeholder="搜索">
</div>
<button type="submit" class="btn btn-info">搜索</button> </form>
<a href="/tadd/" class="btn btn-success pull-right" style="margin-right: 15px;margin-top:8px ">网页添加</a>
<button type="submit" class="btn btn-success pull-right" style="margin-right: 15px;margin-top:8px " data-toggle="modal" data-target="#myModal">添加</button>
</div>
<div class="modal fade j" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog j" role="document">
<div class="modal-content j">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
<h4 class="modal-title" id="myModalLabel">信息填写</h4>
</div>
<div class="modal-body">
<form action="">
<div class="form-group">
<label for="d1">姓名</label>
<input type="text" class="hui form-control" id="d1" autocomplete="off">
</div>
<span id="error-msg"></span>
<div class="form-group">
<label class=" control-label">所带班级</label> <div class="checkbox">
{% for csl in cs_list %}
<label>
<input type="checkbox" value="{{ csl.cid }}" name='check' autocomplete="off">
{{ csl.cname }}
</label>
{% endfor %}
</div>
</div>
<div class="modal-footer">
<button class="an btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="anq btn btn-primary" id="jiao">确认添加</button>
</div>
</form>
</div> </div>
</div>
</div> {#<编辑modal>#}
<div class="modal fade j" id="edit_myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog j" role="document">
<div class="modal-content j">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
<h4 class="modal-title" id="myModalLabel">信息填写</h4>
</div>
<div class="modal-body">
<form action="">
<div class="form-group">
<label for="ed1">姓名</label>
<input type="text" id="ed5" style="display: none">
<input type="text" class="hui form-control" id="ed1">
</div>
<span id="error-msg-e"></span>
<div class="form-group">
<label class=" control-label">所带班级</label> <div class="checkbox">
{% for csl in cs_list %}
<label>
<input type="checkbox" value="{{ csl.cid }}" name='checkc'>
{{ csl.cname }}
</label>
{% endfor %}
</div>
</div>
<div class="modal-footer">
<button class="an btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="anq btn btn-primary" id="xiu">确认修改</button>
</div>
</form>
</div> </div>
</div>
</div>
{#</编辑modal>#} <div class="table-responsive">
<table class="table table-striped table-bordered">
<thead>
<tr>
<th class="col-sm-1">#</th>
<th>教师名</th>
<th>所带班级</th>
<th>操作</th>
</tr>
</thead>
<tbody>
{% for teacher in teacher_list %}
<tr>
<td class="col-sm-1">{{ teacher.td}}</td>
<td>{{ teacher.tn }}</td>
<td cid="{{ teacher.cd }}">{{ teacher.cn }}</td>
<td class="col-sm-8 ">
<a href="/tdelete/?t_id={{ teacher.td }}" class="del btn btn-danger col-sm-offset-3 glyphicon glyphicon-remove">删除</a>
<a href="/tedit/?t_id={{ teacher.td }}" class="w btn btn-success glyphicon glyphicon-pencil">编辑</a>
<button class="wm btn btn-success glyphicon glyphicon-pencil">modal编辑</button>
<button id="sweetd" class="del btn btn-danger glyphicon glyphicon-remove">页面删除</button></td>
</tr>
{% empty %}
<tr><td colspan="3" style="text-align: center">没有数据</td></tr>
{% endfor %}
</tbody>
</table>
</div> <nav aria-label="Page navigation" class=" pull-right">
<ul class="pagination">
<li>
<a href="#" aria-label="Previous">
<span aria-hidden="true">&laquo;</span>
</a>
</li>
<li><a href="#">1</a></li>
<li><a href="#">2</a></li>
<li><a href="#">3</a></li>
<li><a href="#">4</a></li>
<li><a href="#">5</a></li>
<li>
<a href="#" aria-label="Next">
<span aria-hidden="true">&raquo;</span>
</a>
</li>
</ul>
</nav>
</div>
</div>
</div>
</div>
</div> <!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="/static/Dashboard%20Temp_files/jquery.js"></script>
<script>window.jQuery || document.write('<script src="../../assets/js/vendor/jquery.min.js"><\/script>')</script>
<script src="/static/Dashboard%20Temp_files/bootstrap.js"></script>
<!-- Just to make our placeholder images work. Don't actually copy the next line! -->
<script src="/static/Dashboard%20Temp_files/holder.js"></script>
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<script src="/static/Dashboard%20Temp_files/ie10-viewport-bug-workaround.js"></script>
<script src="/static/sweetalert/sweetalert.min.js"></script>
<script>
$("#jiao").on("click",function () {
var tname=$("#d1").val();
var checkID = [];
$("input[name='check']:checked").each(function(i){//把所有被选中的复选框的值存入数组
checkID[i] =$(this).val();
});
var cck=JSON.stringify(checkID);
$.ajax({
url:"/modal_add_teacher/",
type:"post",
data:{"teachername":tname,"checkid":cck},
success:function (data) {
{# }#}
if(data=='OK'){
location.reload()
}
else
{
$("#error-msg").text(data).parent().parent().addClass("has-error");
}
} })
}); {# 编辑modal:#}
$(".wm").on("click",function () {
$sz=$(this).parent().parent().children();
$("#ed1").val($($sz[1]).text());
$("#ed5").val($($sz[0]).text());
zhi=$($sz[2]).attr("cid");
xinzhi=zhi.split(',');
console.log(xinzhi);
for (i=0;i<xinzhi.length;i++){
$inb=$("input[name='checkc']");
for(j=0;j<$inb.length;j++){
if($($inb[j]).val()==xinzhi[i]){
$($inb[j]).attr("checked",true);
}
}
}
$("#edit_myModal").modal("show");
}); $("#xiu").on("click",function () {
var tname=$("#ed1").val();
var tid = $("#ed5").val();
var checkID = [];
$("input[name='checkc']:checked").each(function(i){//把所有被选中的复选框的值存入数组
checkID[i] =$(this).val();
});
var cck=JSON.stringify(checkID);
$.ajax({
url:"/modal_edit_teacher/",
type:"post",
data:{"teachername":tname,"checkid":cck,"tid":tid},
success:function (data) {
{# }#}
if(data=='OK'){
location.reload()
}
else
{
$("#error-msg-e").text(data).parent().parent().addClass("has-error");
}
} })
}); {# 删除开始#}
$("table").on("click" , "#sweetd", function () {
var teacherID = $(this).parent().parent().children().eq(0).text();
var $tr = $(this).parent().parent();
// 弹出sweetalert二次确认框
// swal("1", "2", "warning");
swal({
title: "删除此教师信息?",
text: "删除后无法回复",
type: "warning",
showCancelButton: true,
closeOnConfirm: false,
confirmButtonText: "继续删除!",
confirmButtonColor: "#ec6c62",
cancelButtonText: "再想一想"
}, function (isConfirm) {
if (!isConfirm) return;
$.ajax({
type: "post",
url: "/modal_delete_teacher/",
data: {"teacher_id": teacherID},
success: function (data) {
var dataObj = $.parseJSON(data);
if (dataObj.status === 0) { //后端删除成功
swal("删除成功", dataObj.msg, "success");
$tr.remove() //删除页面中那一行数据
} else {
swal("出错啦。。。", dataObj.msg, "error"); //后端删除失败
}
},
error: function () { // ajax请求失败
swal("啊哦。。。", "服务器走丢了。。。", "error");
}
})
});
}) </script>
<script> </script>
</body></html>

教师页面管理html

与其他页面功能相同,一个教师可以带多个班级,所以添加信息与编辑信息中,使用的是checkbox来进行多选,值得一提:

$("input[name='check']:checked").each(function(i){//把所有被选中的复选框的值存入数组
checkID[i] =$(this).val();
});

这个方法是来获取选中的checkbox的值的

$inb=$("input[name='checkc']");
for(j=0;j<$inb.length;j++){
if($($inb[j]).val()==xinzhi[i]){
$($inb[j]).attr("checked",true);
}}

这个方法是来选中checkbox的,用于在编辑时向用户展示教师现有班级的信息

 def teacher(request):

    conn=pymysql.connect(
host='127.0.0.1',port=3306,
user='root',password='',db='day66',charset='utf8' )
cursor=conn.cursor(cursor=pymysql.cursors.DictCursor)
cursor.execute("select t2.td,t2.tn,group_concat(cname) as cn ,group_concat(cid) as cd from class RIGHT join (select t1.tid as td,t1.tname as tn,class_id from teacher2class INNER join (select tid,tname from teacher)t1 ON teacher2class.teacher_id=t1.tid)t2 on t2.class_id=class.cid GROUP by t2.td")
teacher_list=cursor.fetchall()
cursor.execute("select cid,cname from class")
cs_list = cursor.fetchall()
cursor.close()
conn.close()
return render(request,'teacher.html',{'teacher_list':teacher_list,"cs_list":cs_list})

教师信息展示

拿数据库信息展示时,因为教师可以教多个班级,所以教师在与班级关联的表当中同样的tid会有多条信息,所以联表查询,再用group by分组与group_concat来将同一个教师的班级来进行聚合字符串拼接,这样cn字段拿到的值就是一个教师带的多个班级

def modal_add_teacher(request):
if request.method == "POST":
new_teacher_name = request.POST.get("teachername")
new_class_id = request.POST.get("checkid")
new_class_id=json.loads(new_class_id)
print(new_class_id)
if new_teacher_name:
conn = pymysql.connect(
host='127.0.0.1', port=3306,
user='root', password='', db='day66', charset='utf8'
)
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
cursor.execute("insert into teacher(tname) VALUES (%s)", [new_teacher_name,])
conn.commit()
cursor.close()
conn.close()
conn = pymysql.connect(
host='127.0.0.1', port=3306,
user='root', password='', db='day66', charset='utf8'
)
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
cursor.execute("select * from teacher")
t_clists = cursor.fetchall()[-1]
tc_id=t_clists["tid"]
for item in new_class_id:
itemq = int(item)
cursor.execute("insert into teacher2class(class_id,teacher_id) VALUES (%s,%s)", [itemq, tc_id])
conn.commit()
cursor.close()
conn.close()
return HttpResponse("OK")
else:
error = "班级名称不能为空"
return HttpResponse(error)

教师添加信息

从前端拿值,取到的班级信息的值是一个列表类型的,所以要循环sql语句来进行添加,不光要在教师表添加教师信息,同样在教师与班级关联的表也要添加信息

 def modal_edit_teacher(request):
if request.method == "POST":
new_teacher_name = request.POST.get("teachername")
new_class_id = request.POST.get("checkid")
new_t_id = request.POST.get("tid")
newtd=int(new_t_id)
new_class_id=json.loads(new_class_id)
if new_teacher_name:
conn = pymysql.connect(
host='127.0.0.1', port=3306,
user='root', password='', db='day66', charset='utf8'
)
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
cursor.execute("update teacher set tname=%s where tid=%s", [new_teacher_name,newtd])
conn.commit()
cursor.close()
conn.close()
conn = pymysql.connect(
host='127.0.0.1', port=3306,
user='root', password='', db='day66', charset='utf8'
)
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
cursor.execute("select class_id from teacher2class INNER join (select tid from teacher where tname=%s)t1 on teacher_id = t1.tid",[new_teacher_name])
ret=cursor.fetchall()
li=[]
for it in ret:
li.append(str(it["class_id"]))
old=set(li)
old_new=old.symmetric_difference(new_class_id)
if old_new:
new=(old_new.difference(old))
olds=(old_new.difference(new_class_id))
if new:
for inew in new:
cursor.execute("insert into teacher2class(class_id, teacher_id) VALUES(%s,%s) ", [inew, new_t_id])
if olds:
for iold in olds:
cursor.execute("delete from teacher2class where class_id=%s",[iold])
conn.commit()
cursor.close()
conn.close()
return HttpResponse("OK")
else:
error = "班级名称不能为空"
return HttpResponse(error)

教师编辑信息

这部分代码有两种做法,因为取到的前端的class_id部分的值是字典,所以循环取值,然后通过set集合,来求出旧的class_id的集合与ajax传来的class_id的值的差集,然后再判断如果这个差集中含有接收来的class_id中没有的值那么就是旧的中的值,需要删除,如果是旧的中没有的,就是新的值,需要添加。

第二种方法,直接删除原有的所有在教师与班级关联表中的符合tid值的信息,这样的话这个教师的所有数据就没了,然后再将传来的值直接添加进去。

 def modal_delete_teacher(request):
if request.method == "POST":
new_teacher_gd = request.POST.get("teacher_id")
new_teacher_id=int(new_teacher_gd)
conn = pymysql.connect(
host='127.0.0.1', port=3306,
user='root', password='', db='day66', charset='utf8'
)
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
if new_teacher_gd:
cursor.execute("delete from teacher where tid=%s ", [new_teacher_id])
cursor.execute("delete from teacher2class where teacher_id=%s ", [new_teacher_id])
conn.commit()
cursor.close()
conn.close()
ret=json.dumps({"status":0,"msg":'一鼓作气'})
return HttpResponse(ret) else:
error = "有一些小毛病"
ret = json.dumps({"status": 1, "msg": error})
return HttpResponse(ret)

教师删除信息

删除这部分在前端也引用了sweetalert,在后端的话与添加相同,不止要删除教师表中的信息,更要删除关联表中的信息

本实例的数据库表结构:

其中student表中的class_id关联了class表中的cid,关联表为多对多的关联关系,关联教师表与班级表

Django--网页管理实例解析的更多相关文章

  1. django后台管理-ModelAdmin对象

    Django最强大的部分之一是自动生成的管理后台界面. 它从你的模型中读取元数据,以提供一个快速的.以模型为中心的界面,信任的用户可以在这里管理你网站上的内容. 建议管理后台仅作为组织的一个内部管理工 ...

  2. Android实例-Delphi开发蓝牙官方实例解析(XE10+小米2+小米5)

    相关资料:1.http://blog.csdn.net/laorenshen/article/details/411498032.http://www.cnblogs.com/findumars/p/ ...

  3. Maven--多模块依赖实例解析(五)

    <Maven--搭建开发环境(一)> <Maven--构建企业级仓库(二)> <Maven—几个需要补充的问题(三)> <Maven—生命周期和插件(四)&g ...

  4. Django项目实践4 - Django网站管理(后台管理员)

    http://blog.csdn.net/pipisorry/article/details/45079751 上篇:Django项目实践3 - Django模型 Introduction 对于某一类 ...

  5. Django项目实践4 - Django站点管理(后台管理员)

    http://blog.csdn.net/pipisorry/article/details/45079751 上篇:Django项目实践3 - Django模型 Introduction 对于某一类 ...

  6. Django Rest framework 之 解析器

    RESTful 规范 django rest framework 之 认证(一) django rest framework 之 权限(二) django rest framework 之 节流(三) ...

  7. Django admin 管理工具

    admin 组件的使用 Django 提供了基于 web 的管理工具.Django 自动管理工具是 django.contrib 的一部分. INSTALLED_APPS = [ 'django.co ...

  8. 实例解析Docker数据卷+数据卷容器+flocker数据共享+DockerHub操作

    Docker内部数据管理和Docker之间的数据共享为数据卷和数据卷容器,实例解析1.将本地的文件作为容器的数据卷,2.数据卷flocker插件实现容器集群(或者Docker Swarm)的数据共享3 ...

  9. Django——admin管理工具

    一.admin组件使用 Django 提供了基于 web 的管理工具. Django 自动管理工具是 django.contrib 的一部分.你可以在项目的 settings.py 中的 INSTAL ...

随机推荐

  1. 【11】vue router 之导航钩子

    导航钩子 vue-router 提供的导航钩子主要用来拦截导航,让它完成跳转或取消.有多种方式可以在路由导航发生时执行钩子:全局的, 单个路由独享的, 或者组件级的.http://www.jiansh ...

  2. 安装最新版本的cocoapods

    因为公司的iOS项目使用了cocoapods来管理第三方库,所以要求所有组员的cocoapods版本一致.一般的就是执行: $ sudo gem install -n /usr/local/bin c ...

  3. pat 甲级 1127. ZigZagging on a Tree (30)

    1127. ZigZagging on a Tree (30) 时间限制 400 ms 内存限制 65536 kB 代码长度限制 16000 B 判题程序 Standard 作者 CHEN, Yue ...

  4. 洛谷P1966 火柴排队[NOIP提高组2013]

    我确信我应该是做过这道题……就当再写一遍好了. 贪心思想,一番证明得出a和b数组中最小对最小,次小对次小……时解最优.那么先处理出a,b之间的对应关系,然后按照该关系求a或者b的逆序对数量就是答案 / ...

  5. UVa 11234 The Largest Clique

    找最长的连接的点的数量.用tarjan缩点,思考可知每一个强连通分量里的点要么都选,要么都不选(走别的路),可以动规解决. #include<iostream> #include<c ...

  6. Mongoose 表实例

    /********** 用户表 BY Jaysir 2015.6.21 *********** *********** 可搜索以下关键词来查看未实现功能 *********** *********** ...

  7. 《Linux命令行与shell脚本编程大全 第3版》Linux命令行---13

    以下为阅读<Linux命令行与shell脚本编程大全 第3版>的读书笔记,为了方便记录,特地与书的内容保持同步,特意做成一节一次随笔,特记录如下:

  8. 01.mp4v2应用—mp4转h264

    1.h264文件基本功能 NAL 头 0x00 0x00 0x00 0x01 sps :nal+0x67开头 pps :nal+0x68开头 I帧 0x65 开头 ...... 2.mp4v2提取26 ...

  9. hdu 5055(模拟)

    Bob and math problem Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Oth ...

  10. LeetCode OJ-- Maximum Depth of Binary Tree

    https://oj.leetcode.com/problems/maximum-depth-of-binary-tree/ 求二叉树的最大深度 深度优先搜索 /** * Definition for ...