Django--網頁管理實例解析

此篇為代碼流程的注釋以及自己寫的小項目的思路:

首先是項目的路由配置:

 1 urlpatterns = [
 2     # url(r'^admin/', admin.site.urls),
 3     url(r'^yemian/',yemian),
 4     url(r'^zuoye/',zuoye),
 5     url(r'^class/',views.class_list),
 6     url(r'^class_add/',views.class_add),
 7     url(r'^class_delete/',views.class_delete),
 8     url(r'^class_edit/',views.class_edit),
 9     url(r'^teacher/',tvi.teacher),
10     url(r'^tadd/',tvi.t_add),
11     url(r'^tedit/',tvi.t_edit),
12     url(r'^tdelete/',tvi.t_delete),
13     url(r'^student/',svi.student),
14     url(r'^sadd/',svi.s_add),
15     url(r'^sedit/',svi.s_edit),
16     url(r'^sdelete/',svi.s_delete),
17     url(r'^modal_add_student/', svi.modal_add_student),
18     url(r'^modal_add_teacher/', tvi.modal_add_teacher),
19 
20     url(r'^modal_add_class/', modal_add_class),
21 
22     url(r'^edit_modal_class/', views.edit_modal_add_class),
23     url(r'^modal_edit_student/', svi.modal_edit_student),
24 
25     url(r'^modal_delete_student/', svi.modal_delete_student),
26 
27     url(r'^modal_edit_teacher/', tvi.modal_edit_teacher),
28     url(r'^modal_delete_teacher/', tvi.modal_delete_teacher),
29 
30 ]
項目路由

路由的配置很重要,關乎于前端與后端的交互通道,路由的前面用正則匹配頁面信息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表單的提交,將賬號密碼提交到后端進行判斷,判斷正確跳轉網頁,判斷失敗就提升錯誤信息,下面是相關的函數代碼:

 1 def zuoye(request):
 2     global i
 3     i=i+1
 4     if request.method == "GET":
 5         return render(request, "zuoye.html")
 6     else:
 7         if request.POST.get("username") == "gaoshengyue" and request.POST.get("password") == "gsy121994":
 8             # 登陸成功
 9             return redirect("/class/")
10         else:
11             if i>2:
12              return render(request, "zuoye.html", {"error_msg": "輸入錯誤"})
13             else:
14                 return render(request, "zuoye.html")
登錄跳轉后端py

函數中先進行判斷,如果是get請求就開始用render渲染頁面,render第一個是傳的參數request,第二個是要渲染的頁面,第三個是要返回給頁面的值,也就是我們模板語言要通過

{{}}來取到的值,用字典的形式傳。

用.POST.get來取值,傳值的時候表單中的input有name所以字典的key就是這些name,對應的值就是傳的值,然后進行判斷,登錄成功的話跳轉到主頁面class_list,用redirect來跳轉

主頁面class_listhtm代碼如下:

  1 <!DOCTYPE html>
  2 <html lang="zh-CN"><head>
  3 <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  4     <meta charset="utf-8">
  5     <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6     <meta name="viewport" content="width=device-width, initial-scale=1">
  7   <link rel="stylesheet" href="/static/dist/css/bootstrap.css">
  8     <!-- 上述3個meta標簽*必須*放在最前面,任何其他內容都*必須*跟隨其后! -->
  9     <meta name="description" content="">
 10     <meta name="author" content="">
 11     <link rel="icon" href="http://v3.bootcss.com/favicon.ico">
 12     <title>Dashboard Template for Bootstrap</title>
 13 
 14     <!-- Bootstrap core CSS -->
 15     <link href="/static/Dashboard%20Temp_files/bootstrap.css" rel="stylesheet">
 16 
 17     <!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
 18     <link href="/static/Dashboard%20Temp_files/ie10-viewport-bug-workaround.css" rel="stylesheet">
 19 
 20     <!-- Custom styles for this template -->
 21     <link href="/static/Dashboard%20Temp_files/dashboard.css" rel="stylesheet">
 22 
 23     <!-- Just for debugging purposes. Don't actually copy these 2 lines! -->
 24     <!--[if lt IE 9]><script src="../../assets/js/ie8-responsive-file-warning.js"></script><![endif]-->
 25     <script src="/static/Dashboard%20Temp_files/ie-emulation-modes-warning.js"></script>
 26 
 27     <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
 28     <!--[if lt IE 9]>
 29       <script src="https://cdn.bootcss.com/html5shiv/3.7.3/html5shiv.min.js"></script>
 30       <script src="https://cdn.bootcss.com/respond.js/1.4.2/respond.min.js"></script>
 31     <![endif]-->
 32   </head>
 33 <style>
 34   .col-centered {
 35                   float: none;
 36                   margin: 0 auto;
 37                 }
 38   .cd{
 39     background-color: black;
 40   }
 41 </style>
 42   <body>
 43 
 44     <nav class="navbar navbar-inverse navbar-fixed-top">
 45       <div class="container-fluid">
 46         <div class="navbar-header">
 47           <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
 48             <span class="sr-only">Toggle navigation</span>
 49             <span class="icon-bar"></span>
 50             <span class="icon-bar"></span>
 51             <span class="icon-bar"></span>
 52           </button>
 53           <a class="navbar-brand" href="#">Project name</a>
 54         </div>
 55         <div id="navbar" class="navbar-collapse collapse">
 56           <ul class="nav navbar-nav navbar-right">
 57             <li><a href="#">Dashboard</a></li>
 58             <li><a href="#">Settings</a></li>
 59             <li><a href="#">Profile</a></li>
 60             <li><a href="#">Help</a></li>
 61           </ul>
 62           <form class="navbar-form navbar-right">
 63             <input class="form-control" placeholder="Search..." type="text">
 64           </form>
 65         </div>
 66       </div>
 67     </nav>
 68 
 69     <div class="container-fluid">
 70       <div class="row">
 71         <div class="col-sm-3 col-md-2 sidebar">
 72 
 73           <div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true">
 74   <div class="panel panel-default">
 75     <div class="panel-heading  cd" role="tab" id="headingOne">
 76       <h4 class="panel-title">
 77         <a data-toggle="collapse"  href="/class/" id="classfl">
 78           班級
 79         </a>
 80       </h4>
 81     </div>
 82   </div>
 83   <div class="panel panel-default">
 84     <div class="panel-heading" role="tab" id="headingTwo">
 85       <h4 class="panel-title">
 86         <a class="collapsed"   href="/teacher/" >
 87           教師
 88         </a>
 89       </h4>
 90     </div>
 91   </div>
 92   <div class="panel panel-default">
 93     <div class="panel-heading" role="tab" id="headingThree">
 94       <h4 class="panel-title">
 95         <a class="collapsed"  href="/student/"  aria-controls="collapseThree">
 96           學生
 97         </a>
 98       </h4>
 99     </div>
100   </div>
101 </div>
102 
103         </div>
104         <div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
105 
106 
107           <div class="panel panel-default">
108   <div class="panel-heading">Panel heading</div>
109   <div class="panel-body">
110     <div class="row">
111     <form class="navbar-form navbar-left col-sm-12" role="search">
112   <div class="form-group">
113     <input type="text" class="form-control" placeholder="搜索">
114   </div>
115   <button type="submit" class="btn btn-info">搜索</button>
116 
117 </form>
118         <a href="/class_add/" class="btn btn-success pull-right" style="margin-right: 15px;margin-top:8px ">網頁添加</a>
119 <button type="submit" class="btn btn-success pull-right" style="margin-right: 15px;margin-top:8px " data-toggle="modal" data-target="#myModal">添加</button>
120       </div>
121     <div class="modal fade j" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
122   <div class="modal-dialog j" role="document">
123     <div class="modal-content j">
124       <div class="modal-header">
125         <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
126         <h4 class="modal-title" id="myModalLabel">信息填寫</h4>
127       </div>
128       <div class="modal-body">
129           <form method="post">
130         <div class="form-group">
131     <label for="d1">姓名</label>
132     <input type="text" class="hui form-control" id="d1">
133             <span id="error-msg"></span>
134 <div class="modal-footer">
135     <button class="an btn btn-default" data-dismiss="modal" >Close</button>
136     <button id="modal-submitt" class="anq btn btn-primary" type="button" >提交</button>
137       </div>
138         </div>
139               </form>
140       </div>
141 
142     </div>
143   </div>
144 </div>
145 
146 
147 {#  <edit_modal>#}
148     <div class="modal fade j" id="edit_myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
149   <div class="modal-dialog j" role="document">
150     <div class="modal-content j">
151       <div class="modal-header">
152         <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
153         <h4 class="modal-title" id="myModalLabel">信息填寫</h4>
154       </div>
155       <div class="modal-body">
156           <form>
157 
158         <div class="form-group">
159             <input  type="text" style="display: none" id="ed2">
160     <label for="ed1">班級名</label>
161     <input type="text" class="hui form-control" id="ed1">
162             <span id="edit_error-msg"></span>
163 <div class="modal-footer">
164     <button class="an btn btn-default" data-dismiss="modal" >Close</button>
165     <button id="edit_modal-submitt" class="anq btn btn-primary" type="button" >提交</button>
166       </div>
167         </div>
168               </form>
169       </div>
170 
171     </div>
172   </div>
173 </div>
174 {#  </edit_modal>#}
175      <div class="table-responsive">
176             <table class="table table-striped table-bordered">
177               <thead>
178                 <tr>
179                   <th class="col-sm-1">#</th>
180                   <th>班級名</th>
181                   <th>操作</th>
182                 </tr>
183               </thead>
184               <tbody>
185               {% for class in class_list %}
186                 <tr>
187                   <td class="col-sm-1">{{ class.cid}}</td>
188                   <td>{{ class.cname }}</td>
189                   <td class="col-sm-6 ">
190                       <a href="/class_delete/?class_id={{ class.cid }}" class="del btn btn-danger col-sm-offset-3 glyphicon glyphicon-remove">刪除</a>
191                             <a href="/class_edit/?class_id={{ class.cid }}" class="w btn btn-success glyphicon glyphicon-pencil">編輯</a>
192                   <button class="wm btn btn-success glyphicon glyphicon-pencil">modal編輯</button>
193                   </td>
194 
195                 </tr>
196                 {% endfor %}
197               </tbody>
198             </table>
199           </div>
200 
201 
202     <nav aria-label="Page navigation" class=" pull-right">
203   <ul class="pagination">
204     <li>
205       <a href="#" aria-label="Previous">
206         <span aria-hidden="true">&laquo;</span>
207       </a>
208     </li>
209     <li><a href="#">1</a></li>
210     <li><a href="#">2</a></li>
211     <li><a href="#">3</a></li>
212     <li><a href="#">4</a></li>
213     <li><a href="#">5</a></li>
214     <li>
215       <a href="#" aria-label="Next">
216         <span aria-hidden="true">&raquo;</span>
217       </a>
218     </li>
219   </ul>
220 </nav>
221         </div>
222       </div>
223     </div>
224   </div>
225     </div>
226 
227 
228     <!-- Bootstrap core JavaScript
229     ================================================== -->
230     <!-- Placed at the end of the document so the pages load faster -->
231     <script src="/static/Dashboard%20Temp_files/jquery.js"></script>
232     <script>window.jQuery || document.write('<script src="../../assets/js/vendor/jquery.min.js"><\/script>')</script>
233     <script src="/static/Dashboard%20Temp_files/bootstrap.js"></script>
234     <!-- Just to make our placeholder images work. Don't actually copy the next line! -->
235     <script src="/static/Dashboard%20Temp_files/holder.js"></script>
236     <!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
237     <script src="/static/Dashboard%20Temp_files/ie10-viewport-bug-workaround.js"></script>
238 
239 <script>
240 
241 
242       $("#modal-submitt").on("click", function () {
243 {#        $("#myModal form").submit();#}
244             var className = $("#d1").val();
245             console.log(className);
246 {#          用AJAX不刷新頁面提交到后端#}
247           $.ajax({
248               url: "/modal_add_class/",
249               type: "post",
250               data: {"classname": className},
251               success: function (data) {
252                   if (data === "OK"){
253 {#                                        if (data.length != 0) {#}
254 {#                      var clasData = JSON.parse(data);#}
255 {#                      var newTr = document.createElement("tr");#}
256 {#                      $(newTr).append("<td>" + clasData["id"] + "</td>");#}
257 {#                      $(newTr).append("<td>" + clasData["name"] + "</td>");#}
258 {#                      $("td:last").clone().appendTo($(newTr));#}
259 {#                      $(newTr).appendTo("tbody");#}
260                       location.href="/class/";
261                   }else {
262                       $("#error-msg").text(data).parent().parent().addClass("has-error");
263                   }
264               }
265           })
266       });
267 
268        $(".wm").on("click", function () {
269            $tdz=$(this).parent().parent().children();
270            ce_id=$($tdz[0]).text();
271            ce_name=$($tdz[1]).text();
272         $("#edit_myModal").modal("show");
273          $("#ed2").val(ce_id);
274          $("#ed1").val(ce_name);
275 {#           .find("#ed1").val(ce_name)#}
276       });
277        $("#edit_modal-submitt").on("click",function () {
278            var class_d=$("#ed2").val();
279            var class_n=$("#ed1").val();
280            $.ajax({
281                url:"/edit_modal_class/",
282                type:"post",
283                data:{"class_d":class_d,"class_n":class_n},
284                success:function (data) {
285                 if (data==='OK'){
286                     location.reload()
287                 }
288                 else {
289                     $("#edit_error-msg").text(data).parent().parent().addClass("has-error");
290                 }
291                }
292            })
293        })
294 
295 </script>
296 </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選擇器來取值,下面貼的是后端再班級管理頁面的代碼:

 1 def student(request):
 2 
 3    conn=pymysql.connect(
 4        host='127.0.0.1',port=3306,
 5        user='root',password='',db='day66',charset='utf8'
 6 
 7    )
 8    cursor=conn.cursor(cursor=pymysql.cursors.DictCursor)
 9    cursor.execute("select student.id,student.sname,class.cname,student.class_id from student INNER JOIN  class on student.class_id = class.cid")
10    student_list=cursor.fetchall()
11    cursor.execute("select cid,cname from class")
12    cs_list = cursor.fetchall()
13    cursor.close()
14    conn.close()
15    return  render(request,'student.html',{'student_list':student_list,"cs_list":cs_list})
主頁面渲染

通過連接數據庫,然后通過sql語句來獲取數據庫中的班級信息值,然后傳給前端,前端再通過模板語言來進行展示

 1 def modal_add_class(request):
 2     print(request.method)
 3     if request.method == "POST":
 4         print()
 5         new_class_name = request.POST.get("classname")
 6         if new_class_name:
 7             conn = pymysql.connect(
 8                 host='127.0.0.1', port=3306,
 9                 user='root', password='', db='day66', charset='utf8'
10             )
11             cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
12             cursor.execute("insert into class(cname) VALUES (%s)", [new_class_name,])
13             conn.commit()
14             cursor.close()
15             conn.close()
16             return HttpResponse("OK")
17         else:
18             error = "班級名稱不能為空"
19             return HttpResponse(error)
主頁面添加班級信息

這部分函數通過ajax傳過來的值,用.POST.get(字典的ey)的方式獲取,然后用sql語句insert into后端的數據庫中,然后返回前端OK,前端判斷接受回的消息是OK,就刷新頁面,這樣主頁面再次回到渲染函數,渲染出來的就是包括新添加數據的頁面了。

接下來是班級信息的編輯:

 1 def edit_modal_add_class(request):
 2     if request.method == "POST":
 3         new_class_d = request.POST.get("class_d")
 4         new_class_n = request.POST.get("class_n")
 5         if new_class_n:
 6             conn = pymysql.connect(
 7                 host='127.0.0.1', port=3306,
 8                 user='root', password='', db='day66', charset='utf8'
 9             )
10             cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
11             cursor.execute("update class set cname=%s where cid=%s ", [new_class_n,new_class_d ])
12             conn.commit()
13             cursor.close()
14             conn.close()
15             return HttpResponse("OK")
16         else:
17             error = "班級名稱不能為空"
18             return HttpResponse(error)
主頁面編輯班級信息

這部分函數,同樣是接受ajax傳來的值,然后用sql語句的update來進行數據的更新

下面是學生信息部分的添加、編輯、與刪除。

  1 <!DOCTYPE html>
  2 <html lang="zh-CN"><head>
  3 <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  4     <meta charset="utf-8">
  5     <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6     <meta name="viewport" content="width=device-width, initial-scale=1">
  7   <link rel="stylesheet" href="/static/dist/css/bootstrap.css">
  8     <!-- 上述3個meta標簽*必須*放在最前面,任何其他內容都*必須*跟隨其后! -->
  9     <meta name="description" content="">
 10     <meta name="author" content="">
 11     <link rel="icon" href="http://v3.bootcss.com/favicon.ico">
 12     <title>Dashboard Template for Bootstrap</title>
 13 
 14     <!-- Bootstrap core CSS -->
 15     <link href="/static/Dashboard%20Temp_files/bootstrap.css" rel="stylesheet">
 16 
 17     <!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
 18     <link href="/static/Dashboard%20Temp_files/ie10-viewport-bug-workaround.css" rel="stylesheet">
 19      <link href="/static/sweetalert/sweetalert.css" rel="stylesheet">
 20 
 21     <!-- Custom styles for this template -->
 22     <link href="/static/Dashboard%20Temp_files/dashboard.css" rel="stylesheet">
 23 
 24     <!-- Just for debugging purposes. Don't actually copy these 2 lines! -->
 25     <!--[if lt IE 9]><script src="../../assets/js/ie8-responsive-file-warning.js"></script><![endif]-->
 26     <script src="/static/Dashboard%20Temp_files/ie-emulation-modes-warning.js"></script>
 27 
 28     <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
 29     <!--[if lt IE 9]>
 30       <script src="https://cdn.bootcss.com/html5shiv/3.7.3/html5shiv.min.js"></script>
 31       <script src="https://cdn.bootcss.com/respond.js/1.4.2/respond.min.js"></script>
 32     <![endif]-->
 33   </head>
 34 <style>
 35   .col-centered {
 36                   float: none;
 37                   margin: 0 auto;
 38                 }
 39   .cd{
 40     background-color: black;
 41   }
 42 </style>
 43   <body>
 44 
 45     <nav class="navbar navbar-inverse navbar-fixed-top">
 46       <div class="container-fluid">
 47         <div class="navbar-header">
 48           <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
 49             <span class="sr-only">Toggle navigation</span>
 50             <span class="icon-bar"></span>
 51             <span class="icon-bar"></span>
 52             <span class="icon-bar"></span>
 53           </button>
 54           <a class="navbar-brand" href="#">Project name</a>
 55         </div>
 56         <div id="navbar" class="navbar-collapse collapse">
 57           <ul class="nav navbar-nav navbar-right">
 58             <li><a href="#">Dashboard</a></li>
 59             <li><a href="#">Settings</a></li>
 60             <li><a href="#">Profile</a></li>
 61             <li><a href="#">Help</a></li>
 62           </ul>
 63           <form class="navbar-form navbar-right">
 64             <input class="form-control" placeholder="Search..." type="text">
 65           </form>
 66         </div>
 67       </div>
 68     </nav>
 69 
 70     <div class="container-fluid">
 71       <div class="row">
 72         <div class="col-sm-3 col-md-2 sidebar">
 73 
 74           <div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true">
 75   <div class="panel panel-default">
 76     <div class="panel-heading  cd" role="tab" id="headingOne">
 77       <h4 class="panel-title">
 78         <a  href="/class/" id="classfl">
 79           班級
 80         </a>
 81       </h4>
 82     </div>
 83   </div>
 84   <div class="panel panel-default">
 85     <div class="panel-heading" role="tab" id="headingTwo">
 86       <h4 class="panel-title">
 87         <a class="collapsed"  href="/teacher/" aria-controls="collapseTwo">
 88           教師
 89         </a>
 90       </h4>
 91     </div>
 92   </div>
 93   <div class="panel panel-default">
 94     <div class="panel-heading" role="tab" id="headingThree">
 95       <h4 class="panel-title">
 96         <a class="collapsed"  href="/student/" aria-controls="collapseThree">
 97           學生
 98         </a>
 99       </h4>
100     </div>
101   </div>
102 </div>
103 
104         </div>
105         <div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
106 
107 
108           <div class="panel panel-default">
109   <div class="panel-heading">Panel heading</div>
110   <div class="panel-body">
111     <div class="row">
112     <form class="navbar-form navbar-left col-sm-12" role="search">
113   <div class="form-group">
114     <input type="text" class="form-control" placeholder="搜索">
115   </div>
116   <button type="submit" class="btn btn-info">搜索</button>
117 
118 </form>
119         <a href="/sadd/" class="btn btn-success pull-right" style="margin-right: 15px;margin-top:8px ">網頁添加</a>
120 <button class="btn btn-success pull-right" style="margin-right: 15px;margin-top:8px " data-toggle="modal" data-target="#myModal">添加</button>
121       </div>
122     <div class="modal fade j" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
123   <div class="modal-dialog j" role="document">
124     <div class="modal-content j">
125       <div class="modal-header">
126         <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
127         <h4 class="modal-title" id="myModalLabel">信息填寫</h4>
128       </div>
129       <div class="modal-body">
130           <form>
131         <div class="form-group">
132     <label for="d1">學生名</label>
133     <input type="text" class="hui form-control" id="d1">
134             </div>
135          <div class="form-group">
136     <label for="d3" class=" control-label">班級id</label>
137         <select class="form-control" name="sclass">
138             {% for csl in cs_list %}
139           <option value="{{ csl.cid }}">{{ csl.cname }}</option>
140             {% endfor %}
141 </select>
142     </div>
143           <span id="error-msg"></span>
144 <div class="modal-footer">
145     <button class="an btn btn-default" data-dismiss="modal">Close</button>
146     <button class="anq btn btn-primary" id="modal-submit" type="button" >確定添加</button>
147       </div>
148               </form>
149       </div>
150 
151     </div>
152   </div>
153 </div>
154 
155 
156 {#  <modaladd>#}
157 <div class="modal fade j" id="edit_myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
158   <div class="modal-dialog j" role="document">
159     <div class="modal-content j">
160       <div class="modal-header">
161         <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
162         <h4 class="modal-title" id="myModalLabel">信息填寫</h4>
163       </div>
164       <div class="modal-body">
165           <form>
166         <div class="form-group">
167             <input type="text" style="display: none" id="ed3">
168     <label for="d1">學生名</label>
169     <input type="text" class="hui form-control" id="ed1">
170             </div>
171          <div class="form-group">
172     <label for="edit_sele" class=" control-label">班級id</label>
173         <select class="form-control" id="edit_sele">
174             {% for csl in cs_list %}
175           <option value="{{ csl.cid }}">{{ csl.cname }}</option>
176             {% endfor %}
177         </select>
178     </div>
179           <span id="error-msg"></span>
180 <div class="modal-footer">
181     <button class="an btn btn-default" data-dismiss="modal">Close</button>
182     <button class="anq btn btn-primary" id="edit-modal-submit" type="button" >確定修改</button>
183       </div>
184               </form>
185       </div>
186 
187     </div>
188   </div>
189 </div>
190 
191 {#  </modaladd>#}
192 
193   <div class="table-responsive">
194             <table class="table table-striped table-bordered">
195               <thead>
196                 <tr>
197                   <th class="col-sm-1">#</th>
198                   <th>學生名</th>
199                     <th>班級名</th>
200                   <th>操作</th>
201                 </tr>
202               </thead>
203               <tbody>
204               {% for student in student_list %}
205                 <tr>
206                   <td class="col-sm-1">{{ student.id}}</td>
207                   <td>{{ student.sname }}</td>
208                     <td cid="{{ student.class_id }}">{{ student.cname }}</td>
209                   <td class="col-sm-8 ">
210                       <a href="/sdelete/?s_id={{ student.id }}" class="del btn btn-danger col-sm-offset-3 glyphicon glyphicon-remove">刪除</a>
211                             <a href="/sedit/?s_id={{ student.id }}" class="w btn btn-success glyphicon glyphicon-pencil">編輯</a>
212                       <button  class="wm btn btn-success glyphicon glyphicon-pencil">modal編輯</button>
213                       <button id="sweetd" class="del btn btn-danger  glyphicon glyphicon-remove">頁面刪除</button>
214                   </td>
215                 </tr>
216                 {% endfor %}
217               </tbody>
218             </table>
219           </div>
220 
221     <nav aria-label="Page navigation" class=" pull-right">
222   <ul class="pagination">
223     <li>
224       <a href="#" aria-label="Previous">
225         <span aria-hidden="true">&laquo;</span>
226       </a>
227     </li>
228     <li><a href="#">1</a></li>
229     <li><a href="#">2</a></li>
230     <li><a href="#">3</a></li>
231     <li><a href="#">4</a></li>
232     <li><a href="#">5</a></li>
233     <li>
234       <a href="#" aria-label="Next">
235         <span aria-hidden="true">&raquo;</span>
236       </a>
237     </li>
238   </ul>
239 </nav>
240         </div>
241       </div>
242     </div>
243   </div>
244     </div>
245 
246 
247     <!-- Bootstrap core JavaScript
248     ================================================== -->
249     <!-- Placed at the end of the document so the pages load faster -->
250     <script src="/static/Dashboard%20Temp_files/jquery.js"></script>
251     <script>window.jQuery || document.write('<script src="../../assets/js/vendor/jquery.min.js"><\/script>')</script>
252     <script src="/static/Dashboard%20Temp_files/bootstrap.js"></script>
253     <!-- Just to make our placeholder images work. Don't actually copy the next line! -->
254     <script src="/static/Dashboard%20Temp_files/holder.js"></script>
255     <!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
256     <script src="/static/Dashboard%20Temp_files/ie10-viewport-bug-workaround.js"></script>
257     <script src="/static/sweetalert/sweetalert.min.js"></script>
258     <script>
259         $("#modal-submit").on("click", function () {
260 {#            $("#myModal form").submit();#}
261             var studentName = $("#d1").val();
262             var studentId=$("option:selected").val();
263 {#          用AJAX不刷新頁面提交到后端#}
264           $.ajax({
265               url: "/modal_add_student/",
266               type: "POST",
267               data: {"studentname": studentName,"studentid":studentId},
268               success: function (data) {
269                   if (data === "OK"){
270                       location.href="/student/";
271 
272                   }else {
273                       $("#error-msg").text(data).parent().parent().addClass("has-error");
274                   }
275               }
276           })
277       });
278         $(".wm").on("click",function () {
279             $sz=$(this).parent().parent().children();
280             $("#ed1").val($($sz[1]).text());
281             zhi=$($sz[2]).attr("cid");
282             $("#edit_sele").val(zhi);
283             $("#ed3").val($($sz[0]).text());
284             $("#edit_myModal").modal("show");
285         });
286         $("#edit-modal-submit").on("click", function () {
287             var studentName = $("#ed1").val();
288             var studentId=$("#edit_sele option:selected").val();
289             var student_gd=$("#ed3").val();
290 {#          用AJAX不刷新頁面提交到后端#}
291           $.ajax({
292               url: "/modal_edit_student/",
293               type: "POST",
294 
295               data: {"studentname": studentName,"studentid":studentId,"student_gd":student_gd},
296               success: function (data) {
297                   if (data === "OK"){
298                       location.href="/student/";
299 
300                   }else {
301                       $("#error-msg").text(data).parent().parent().addClass("has-error");
302                   }
303               }
304           })
305       });
306 
307 {#        二次刪除     #}
308         $("table").on("click" , "#sweetd", function () {
309         var studentID = $(this).parent().parent().children().eq(0).text();
310         var $tr = $(this).parent().parent();
311         // 彈出sweetalert二次確認框
312         // swal("1", "2", "warning");
313         swal({
314         title: "刪除此學生信息?",
315         text: "刪除后無法回復。",
316         type: "warning",
317         showCancelButton: true,
318         closeOnConfirm: false,
319         confirmButtonText: "繼續刪除!",
320         confirmButtonColor: "#ec6c62",
321         cancelButtonText: "再想一想"
322     }, function (isConfirm) {
323         if (!isConfirm) return;
324         $.ajax({
325             type: "post",
326             url: "/modal_delete_student/",
327             data: {"student_id": studentID},
328             success: function (data) {
329                 var dataObj = $.parseJSON(data);
330                 if (dataObj.status === 0) { //后端刪除成功
331                     swal("刪除成功", dataObj.msg, "success");
332                     $tr.remove()  //刪除頁面中那一行數據
333                 } else {
334                     swal("出錯啦。。。", dataObj.msg, "error");  //后端刪除失敗
335                 }
336             },
337             error: function () {  // ajax請求失敗
338                 swal("啊哦。。。", "服務器走丟了。。。", "error");
339             }
340         })
341     });
342     })
343     </script>
344 </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的官網使用。

 1 def student(request):
 2 
 3    conn=pymysql.connect(
 4        host='127.0.0.1',port=3306,
 5        user='root',password='',db='day66',charset='utf8'
 6 
 7    )
 8    cursor=conn.cursor(cursor=pymysql.cursors.DictCursor)
 9    cursor.execute("select student.id,student.sname,class.cname,student.class_id from student INNER JOIN  class on student.class_id = class.cid")
10    student_list=cursor.fetchall()
11    cursor.execute("select cid,cname from class")
12    cs_list = cursor.fetchall()
13    cursor.close()
14    conn.close()
15    return  render(request,'student.html',{'student_list':student_list,"cs_list":cs_list})
學生信息展示

同樣通過查找數據庫的數據來進行數據展示

 1 def modal_add_student(request):
 2     if request.method == "POST":
 3         new_student_name = request.POST.get("studentname")
 4         new_student_id_=request.POST.get("studentid")
 5         new_student_id_=int(new_student_id_)
 6         conn = pymysql.connect(
 7             host='127.0.0.1', port=3306,
 8             user='root', password='', db='day66', charset='utf8'
 9         )
10         cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
11         if new_student_name:
12             cursor.execute("insert into student(sname,class_id)values (%s,%s)", [new_student_name,new_student_id_])
13             conn.commit()
14             cursor.close()
15             conn.close()
16             return HttpResponse("OK")
17 
18         else:
19             error = "班級名稱不能為空"
20             return HttpResponse(error)
學生信息添加

同班級信息添加,不過這時要添加的就是兩條信息了,所以表的自增ID不用添加。

 1 def modal_edit_student(request):
 2     if request.method == "POST":
 3         new_student_name = request.POST.get("studentname")
 4         new_student_id_=request.POST.get("studentid")
 5         new_student_gd = request.POST.get("student_gd")
 6         new_student_id=int(new_student_id_)
 7         new_student_gd_ = int(new_student_gd)
 8         conn = pymysql.connect(
 9             host='127.0.0.1', port=3306,
10             user='root', password='', db='day66', charset='utf8'
11         )
12         cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
13         if new_student_name:
14             cursor.execute("update student set sname=%s where id=%s ", [new_student_name,new_student_gd])
15             cursor.execute("update student set class_id=%s where id=%s ", [new_student_id, new_student_gd])
16             conn.commit()
17             cursor.close()
18             conn.close()
19             return HttpResponse("OK")
20 
21         else:
22             error = "學生名稱不能為空"
23             return HttpResponse(error)
學生信息編輯

同班級信息編輯差不多,不過修改的時候要帶上class_id

 1 def modal_delete_student(request):
 2     if request.method == "POST":
 3         new_student_gd = request.POST.get("student_id")
 4         new_student_id=int(new_student_gd)
 5         print(new_student_id)
 6         conn = pymysql.connect(
 7             host='127.0.0.1', port=3306,
 8             user='root', password='', db='day66', charset='utf8'
 9         )
10         cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
11         if new_student_gd:
12             cursor.execute("delete from student where id=%s ", [new_student_id])
13             conn.commit()
14             cursor.close()
15             conn.close()
16             ret=json.dumps({"status":0,"msg":'一鼓作氣'})
17             return HttpResponse(ret)
18         else:
19             error = "有一些小毛病"
20             ret = json.dumps({"status": 1, "msg": error})
21             return HttpResponse(ret)
學生信息刪除

返回給前端的是一條字典信息,前面status中是狀態碼,后面的msg中是錯誤信息,前端通過狀態碼來判斷是否修改完成。因為前后端間傳值只能是字符串所以要用json.dumps來序列化一下,前端通過JSON.parse來解析。

下面是比較復雜的教師頁面管理:

  1 <!DOCTYPE html>
  2 <html lang="zh-CN"><head>
  3 <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  4     <meta charset="utf-8">
  5     <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6     <meta name="viewport" content="width=device-width, initial-scale=1">
  7   <link rel="stylesheet" href="/static/dist/css/bootstrap.css">
  8     <!-- 上述3個meta標簽*必須*放在最前面,任何其他內容都*必須*跟隨其后! -->
  9     <meta name="description" content="">
 10     <meta name="author" content="">
 11     <link rel="icon" href="http://v3.bootcss.com/favicon.ico">
 12     <title>Dashboard Template for Bootstrap</title>
 13 
 14     <!-- Bootstrap core CSS -->
 15     <link href="/static/Dashboard%20Temp_files/bootstrap.css" rel="stylesheet">
 16 
 17     <!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
 18     <link href="/static/Dashboard%20Temp_files/ie10-viewport-bug-workaround.css" rel="stylesheet">
 19 
 20     <!-- Custom styles for this template -->
 21     <link href="/static/Dashboard%20Temp_files/dashboard.css" rel="stylesheet">
 22 
 23     <!-- Just for debugging purposes. Don't actually copy these 2 lines! -->
 24     <!--[if lt IE 9]><script src="../../assets/js/ie8-responsive-file-warning.js"></script><![endif]-->
 25     <script src="/static/Dashboard%20Temp_files/ie-emulation-modes-warning.js"></script>
 26     <link href="/static/sweetalert/sweetalert.css" rel="stylesheet">
 27     <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
 28     <!--[if lt IE 9]>
 29       <script src="https://cdn.bootcss.com/html5shiv/3.7.3/html5shiv.min.js"></script>
 30       <script src="https://cdn.bootcss.com/respond.js/1.4.2/respond.min.js"></script>
 31     <![endif]-->
 32   </head>
 33 <style>
 34   .col-centered {
 35                   float: none;
 36                   margin: 0 auto;
 37                 }
 38   .cd{
 39     background-color: black;
 40   }
 41 </style>
 42   <body>
 43 
 44     <nav class="navbar navbar-inverse navbar-fixed-top">
 45       <div class="container-fluid">
 46         <div class="navbar-header">
 47           <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
 48             <span class="sr-only">Toggle navigation</span>
 49             <span class="icon-bar"></span>
 50             <span class="icon-bar"></span>
 51             <span class="icon-bar"></span>
 52           </button>
 53           <a class="navbar-brand" href="#">Project name</a>
 54         </div>
 55         <div id="navbar" class="navbar-collapse collapse">
 56           <ul class="nav navbar-nav navbar-right">
 57             <li><a href="#">Dashboard</a></li>
 58             <li><a href="#">Settings</a></li>
 59             <li><a href="#">Profile</a></li>
 60             <li><a href="#">Help</a></li>
 61           </ul>
 62           <form class="navbar-form navbar-right">
 63             <input class="form-control" placeholder="Search..." type="text">
 64           </form>
 65         </div>
 66       </div>
 67     </nav>
 68 
 69     <div class="container-fluid">
 70       <div class="row">
 71         <div class="col-sm-3 col-md-2 sidebar">
 72 
 73           <div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true">
 74   <div class="panel panel-default">
 75     <div class="panel-heading  cd" role="tab" id="headingOne">
 76       <h4 class="panel-title">
 77         <a  href="/class/" id="classfl">
 78           班級
 79         </a>
 80       </h4>
 81     </div>
 82   </div>
 83   <div class="panel panel-default">
 84     <div class="panel-heading" role="tab" id="headingTwo">
 85       <h4 class="panel-title">
 86         <a class="collapsed"  href="/teacher/" aria-controls="collapseTwo">
 87           教師
 88         </a>
 89       </h4>
 90     </div>
 91   </div>
 92   <div class="panel panel-default">
 93     <div class="panel-heading" role="tab" id="headingThree">
 94       <h4 class="panel-title">
 95         <a class="collapsed"  href="/student/"aria-controls="collapseThree">
 96           學生
 97         </a>
 98       </h4>
 99     </div>
100   </div>
101 </div>
102 
103         </div>
104         <div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
105 
106 
107           <div class="panel panel-default">
108   <div class="panel-heading">Panel heading</div>
109   <div class="panel-body">
110     <div class="row">
111     <form class="navbar-form navbar-left col-sm-12" role="search">
112   <div class="form-group">
113     <input type="text" class="form-control" placeholder="搜索">
114   </div>
115   <button type="submit" class="btn btn-info">搜索</button>
116 
117 </form>
118         <a href="/tadd/" class="btn btn-success pull-right" style="margin-right: 15px;margin-top:8px ">網頁添加</a>
119 <button type="submit" class="btn btn-success pull-right" style="margin-right: 15px;margin-top:8px " data-toggle="modal" data-target="#myModal">添加</button>
120       </div>
121     <div class="modal fade j" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
122   <div class="modal-dialog j" role="document">
123     <div class="modal-content j">
124       <div class="modal-header">
125         <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
126         <h4 class="modal-title" id="myModalLabel">信息填寫</h4>
127       </div>
128       <div class="modal-body">
129           <form action="">
130         <div class="form-group">
131     <label for="d1">姓名</label>
132     <input type="text" class="hui form-control" id="d1" autocomplete="off">
133             </div>
134               <span id="error-msg"></span>
135                <div class="form-group">
136     <label class=" control-label">所帶班級</label>
137 
138         <div class="checkbox">
139             {% for csl in cs_list %}
140           <label>
141             <input type="checkbox" value="{{ csl.cid }}" name='check' autocomplete="off">
142            {{ csl.cname }}
143           </label>
144              {% endfor %}
145         </div>
146     </div>
147 <div class="modal-footer">
148     <button  class="an btn btn-default" data-dismiss="modal">Close</button>
149     <button type="button" class="anq btn btn-primary" id="jiao">確認添加</button>
150       </div>
151               </form>
152       </div>
153 
154     </div>
155   </div>
156 </div>
157 
158 {#<編輯modal>#}
159  <div class="modal fade j" id="edit_myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
160   <div class="modal-dialog j" role="document">
161     <div class="modal-content j">
162       <div class="modal-header">
163         <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
164         <h4 class="modal-title" id="myModalLabel">信息填寫</h4>
165       </div>
166       <div class="modal-body">
167           <form action="">
168         <div class="form-group">
169     <label for="ed1">姓名</label>
170             <input type="text" id="ed5" style="display: none">
171     <input type="text" class="hui form-control" id="ed1">
172             </div>
173               <span id="error-msg-e"></span>
174                <div class="form-group">
175     <label class=" control-label">所帶班級</label>
176 
177         <div class="checkbox">
178             {% for csl in cs_list %}
179           <label>
180             <input type="checkbox" value="{{ csl.cid }}" name='checkc'>
181            {{ csl.cname }}
182           </label>
183              {% endfor %}
184         </div>
185     </div>
186 <div class="modal-footer">
187     <button  class="an btn btn-default" data-dismiss="modal">Close</button>
188     <button type="button" class="anq btn btn-primary" id="xiu">確認修改</button>
189       </div>
190               </form>
191       </div>
192 
193     </div>
194   </div>
195 </div>
196 {#</編輯modal>#}
197 
198   <div class="table-responsive">
199             <table class="table table-striped table-bordered">
200               <thead>
201                 <tr>
202                   <th class="col-sm-1">#</th>
203                   <th>教師名</th>
204                     <th>所帶班級</th>
205                   <th>操作</th>
206                 </tr>
207               </thead>
208               <tbody>
209               {% for teacher in teacher_list %}
210                 <tr>
211                   <td class="col-sm-1">{{ teacher.td}}</td>
212                   <td>{{ teacher.tn }}</td>
213                     <td cid="{{ teacher.cd }}">{{ teacher.cn }}</td>
214                   <td class="col-sm-8 ">
215                       <a href="/tdelete/?t_id={{ teacher.td }}" class="del btn btn-danger col-sm-offset-3 glyphicon glyphicon-remove">刪除</a>
216                             <a href="/tedit/?t_id={{ teacher.td }}" class="w btn btn-success glyphicon glyphicon-pencil">編輯</a>
217                           <button  class="wm btn btn-success glyphicon glyphicon-pencil">modal編輯</button>
218                           <button id="sweetd" class="del btn btn-danger  glyphicon glyphicon-remove">頁面刪除</button></td>
219                 </tr>
220                   {% empty %}
221                   <tr><td colspan="3" style="text-align: center">沒有數據</td></tr>
222                 {% endfor %}
223               </tbody>
224             </table>
225           </div>
226 
227     <nav aria-label="Page navigation" class=" pull-right">
228   <ul class="pagination">
229     <li>
230       <a href="#" aria-label="Previous">
231         <span aria-hidden="true">&laquo;</span>
232       </a>
233     </li>
234     <li><a href="#">1</a></li>
235     <li><a href="#">2</a></li>
236     <li><a href="#">3</a></li>
237     <li><a href="#">4</a></li>
238     <li><a href="#">5</a></li>
239     <li>
240       <a href="#" aria-label="Next">
241         <span aria-hidden="true">&raquo;</span>
242       </a>
243     </li>
244   </ul>
245 </nav>
246         </div>
247       </div>
248     </div>
249   </div>
250     </div>
251 
252 
253     <!-- Bootstrap core JavaScript
254     ================================================== -->
255     <!-- Placed at the end of the document so the pages load faster -->
256     <script src="/static/Dashboard%20Temp_files/jquery.js"></script>
257     <script>window.jQuery || document.write('<script src="../../assets/js/vendor/jquery.min.js"><\/script>')</script>
258     <script src="/static/Dashboard%20Temp_files/bootstrap.js"></script>
259     <!-- Just to make our placeholder images work. Don't actually copy the next line! -->
260     <script src="/static/Dashboard%20Temp_files/holder.js"></script>
261     <!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
262     <script src="/static/Dashboard%20Temp_files/ie10-viewport-bug-workaround.js"></script>
263     <script src="/static/sweetalert/sweetalert.min.js"></script>
264   <script>
265      $("#jiao").on("click",function () {
266          var tname=$("#d1").val();
267          var checkID = [];
268          $("input[name='check']:checked").each(function(i){//把所有被選中的復選框的值存入數組
269            checkID[i] =$(this).val();
270          });
271          var cck=JSON.stringify(checkID);
272          $.ajax({
273              url:"/modal_add_teacher/",
274              type:"post",
275              data:{"teachername":tname,"checkid":cck},
276              success:function (data) {
277 {#                     }#}
278                  if(data=='OK'){
279                      location.reload()
280                  }
281                      else
282                      {
283                          $("#error-msg").text(data).parent().parent().addClass("has-error");
284                      }
285                  }
286 
287              })
288          });
289 
290 {#   編輯modal:#}
291       $(".wm").on("click",function () {
292               $sz=$(this).parent().parent().children();
293             $("#ed1").val($($sz[1]).text());
294              $("#ed5").val($($sz[0]).text());
295             zhi=$($sz[2]).attr("cid");
296             xinzhi=zhi.split(',');
297             console.log(xinzhi);
298             for (i=0;i<xinzhi.length;i++){
299                 $inb=$("input[name='checkc']");
300                 for(j=0;j<$inb.length;j++){
301                 if($($inb[j]).val()==xinzhi[i]){
302                     $($inb[j]).attr("checked",true);
303                 }
304                 }
305             }
306             $("#edit_myModal").modal("show");
307       });
308 
309 
310       $("#xiu").on("click",function () {
311           var tname=$("#ed1").val();
312           var tid = $("#ed5").val();
313          var checkID = [];
314          $("input[name='checkc']:checked").each(function(i){//把所有被選中的復選框的值存入數組
315            checkID[i] =$(this).val();
316          });
317          var cck=JSON.stringify(checkID);
318          $.ajax({
319              url:"/modal_edit_teacher/",
320              type:"post",
321              data:{"teachername":tname,"checkid":cck,"tid":tid},
322              success:function (data) {
323 {#                     }#}
324                  if(data=='OK'){
325                      location.reload()
326                  }
327                      else
328                      {
329                          $("#error-msg-e").text(data).parent().parent().addClass("has-error");
330                      }
331                  }
332 
333              })
334          });
335 
336 
337 {#      刪除開始#}
338       $("table").on("click" , "#sweetd", function () {
339         var teacherID = $(this).parent().parent().children().eq(0).text();
340         var $tr = $(this).parent().parent();
341         // 彈出sweetalert二次確認框
342         // swal("1", "2", "warning");
343         swal({
344         title: "刪除此教師信息?",
345         text: "刪除后無法回復",
346         type: "warning",
347         showCancelButton: true,
348         closeOnConfirm: false,
349         confirmButtonText: "繼續刪除!",
350         confirmButtonColor: "#ec6c62",
351         cancelButtonText: "再想一想"
352     }, function (isConfirm) {
353         if (!isConfirm) return;
354         $.ajax({
355             type: "post",
356             url: "/modal_delete_teacher/",
357             data: {"teacher_id": teacherID},
358             success: function (data) {
359                 var dataObj = $.parseJSON(data);
360                 if (dataObj.status === 0) { //后端刪除成功
361                     swal("刪除成功", dataObj.msg, "success");
362                     $tr.remove()  //刪除頁面中那一行數據
363                 } else {
364                     swal("出錯啦。。。", dataObj.msg, "error");  //后端刪除失敗
365                 }
366             },
367             error: function () {  // ajax請求失敗
368                 swal("啊哦。。。", "服務器走丟了。。。", "error");
369             }
370         })
371     });
372     })
373 
374   </script>
375     <script>
376 
377     </script>
378 </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的,用于在編輯時向用戶展示教師現有班級的信息

 1 def teacher(request):
 2 
 3    conn=pymysql.connect(
 4        host='127.0.0.1',port=3306,
 5        user='root',password='',db='day66',charset='utf8'
 6 
 7    )
 8    cursor=conn.cursor(cursor=pymysql.cursors.DictCursor)
 9    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")
10    teacher_list=cursor.fetchall()
11    cursor.execute("select cid,cname from class")
12    cs_list = cursor.fetchall()
13    cursor.close()
14    conn.close()
15    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語句來進行添加,不光要在教師表添加教師信息,同樣在教師與班級關聯的表也要添加信息

 1 def modal_edit_teacher(request):
 2     if request.method == "POST":
 3         new_teacher_name = request.POST.get("teachername")
 4         new_class_id = request.POST.get("checkid")
 5         new_t_id = request.POST.get("tid")
 6         newtd=int(new_t_id)
 7         new_class_id=json.loads(new_class_id)
 8         if new_teacher_name:
 9             conn = pymysql.connect(
10                 host='127.0.0.1', port=3306,
11                 user='root', password='', db='day66', charset='utf8'
12             )
13             cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
14             cursor.execute("update teacher set tname=%s where tid=%s", [new_teacher_name,newtd])
15             conn.commit()
16             cursor.close()
17             conn.close()
18             conn = pymysql.connect(
19                 host='127.0.0.1', port=3306,
20                 user='root', password='', db='day66', charset='utf8'
21             )
22             cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
23             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])
24             ret=cursor.fetchall()
25             li=[]
26             for it in ret:
27                 li.append(str(it["class_id"]))
28             old=set(li)
29             old_new=old.symmetric_difference(new_class_id)
30             if old_new:
31                 new=(old_new.difference(old))
32                 olds=(old_new.difference(new_class_id))
33                 if new:
34                     for inew in new:
35                         cursor.execute("insert into teacher2class(class_id, teacher_id) VALUES(%s,%s) ", [inew, new_t_id])
36                 if olds:
37                     for iold in olds:
38                         cursor.execute("delete from teacher2class where class_id=%s",[iold])
39                 conn.commit()
40                 cursor.close()
41                 conn.close()
42             return HttpResponse("OK")
43         else:
44             error = "班級名稱不能為空"
45             return HttpResponse(error)
教師編輯信息

?這部分代碼有兩種做法,因為取到的前端的class_id部分的值是字典,所以循環取值,然后通過set集合,來求出舊的class_id的集合與ajax傳來的class_id的值的差集,然后再判斷如果這個差集中含有接收來的class_id中沒有的值那么就是舊的中的值,需要刪除,如果是舊的中沒有的,就是新的值,需要添加。

第二種方法,直接刪除原有的所有在教師與班級關聯表中的符合tid值的信息,這樣的話這個教師的所有數據就沒了,然后再將傳來的值直接添加進去。

 1 def modal_delete_teacher(request):
 2     if request.method == "POST":
 3         new_teacher_gd = request.POST.get("teacher_id")
 4         new_teacher_id=int(new_teacher_gd)
 5         conn = pymysql.connect(
 6             host='127.0.0.1', port=3306,
 7             user='root', password='', db='day66', charset='utf8'
 8         )
 9         cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
10         if new_teacher_gd:
11             cursor.execute("delete from teacher where tid=%s ", [new_teacher_id])
12             cursor.execute("delete from teacher2class where teacher_id=%s ", [new_teacher_id])
13             conn.commit()
14             cursor.close()
15             conn.close()
16             ret=json.dumps({"status":0,"msg":'一鼓作氣'})
17             return HttpResponse(ret)
18 
19         else:
20             error = "有一些小毛病"
21             ret = json.dumps({"status": 1, "msg": error})
22             return HttpResponse(ret)
教師刪除信息

刪除這部分在前端也引用了sweetalert,在后端的話與添加相同,不止要刪除教師表中的信息,更要刪除關聯表中的信息

?

本實例的數據庫表結構:

?

?其中student表中的class_id關聯了class表中的cid,關聯表為多對多的關聯關系,關聯教師表與班級表

轉載于:https://www.cnblogs.com/gaoshengyue/p/7929661.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/251440.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/251440.shtml
英文地址,請注明出處:http://en.pswp.cn/news/251440.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

阿里云ecs實例中創建數據庫

阿里云ecs實例中創建數據庫安裝mysql創建數據庫1.登錄2.新建數據庫3.執行.sql文件4.查詢表&#xff0c;驗證是否創建成功4.退出數據庫安裝mysql 參考https://blog.csdn.net/qq_36350532/article/details/79496049 創建數據庫 1.登錄 mysql -u root -p&#xff08;這里寫密碼…

javascript --- 尾遞歸優化的實現

考慮一個正常的遞歸函數 function sum(x, y) {if (y > 0) {return sum (x 1, y - 1);} else {return x;} } sum(1, 100000000);超出調用棧的最大次數… 下面使用尾遞歸優化實現: function tco(f) {var value ;var active false;var accumulated [];return function acc…

《對不隊》團隊項目用戶驗收評審

任務1&#xff1a;團隊作業Beta沖刺 Beta沖刺第一天&#xff1a;https://www.cnblogs.com/bingoF6/p/9221744.htmlBeta沖刺第二天&#xff1a;https://www.cnblogs.com/bingoF6/p/9226305.htmlBeta沖刺第三天&#xff1a;https://www.cnblogs.com/bingoF6/p/9230815.htmlBeta沖…

部署項目的問題(一)—— vue工程打包上線樣式錯亂問題

1、 打開index.html一片空白 參考&#xff1a;鏈接: link. 修改build對象里的assetsPublicPath為’./’ assetsPublicPath: ./2、ElementUI樣式丟失 參考&#xff1a;鏈接: link. 這里嘗試完前三種&#xff1a; 1.main.js樣式引入順序問題 調整了import的順序&#xff08;…

遲遲發布的軟工實踐兩月感想

第七周&#xff0c;第八周了。 寫幾點反省。 嚴謹。工作的時候&#xff0c;說話行文風格要注意&#xff0c;因為這影響溝通的質量&#xff0c;影響別人對你的評價。會間接影響對方的響應&#xff0c;影響合作。學會主動承擔責任&#xff0c;做受關注的那個人。主動鍛煉自己。開…

構建SpringBoot第一個Demo

使用官方地址生成項目 https://start.spring.io Generate&#xff1a;可以選擇Maven或者Gradle構建項目 語言&#xff1a;我想一般都是Java 接下來選擇SpringBoot的版本&#xff0c;目前比較穩定的1.5.10 GroupID&#xff1a;自定義 Artifact&#xff1a;自定義 Dependencies&…

部署項目的問題(二)—— 阿里云服務器 ECS升級node版本

在運行服務端代碼時報錯&#xff0c;當時報錯的代碼沒copy下來&#xff0c;大概就是如下形式 mbp:hybrid-statistic wfp$ node app.js /Users/wfp/Work/hybrid-statistic/app.js:28 async function responseTime(ctx, next) {^^^^^^^^ SyntaxError: Unexpected token function…

javascript --- Object.assign()淺復制解決方法

Object.assign()是淺復制(即:只復制對象得引用而,而不是新實例).它無法正確復制get屬性和set屬性. 看下面得例子: // 定義一個source對象,含set方法 const source {set foo(value) {console.log(value);} };// 使用Object.assign進行賦值 const target1 {}; Object.assign(t…

微信小程序與Java后臺的通信

一、寫在前面 最近接觸了小程序的開發&#xff0c;后端選擇Java&#xff0c;因為小程序的代碼運行在騰訊的服務器上&#xff0c;而我們自己編寫的Java代碼運行在我們自己部署的服務器上&#xff0c;所以一開始不是很明白小程序如何與后臺進行通信的&#xff0c;然后查找資料發現…

面向對象初識④

抽象類與接口類 接口類 繼承有兩種用途&#xff1a; 一&#xff1a;繼承基類的方法&#xff0c;并且做出自己的改變或者擴展&#xff08;代碼重用&#xff09; 二&#xff1a;聲明某個子類兼容于某基類&#xff0c;定義一個接口類Interface&#xff0c;接口類中定義了一些接口…

部署項目的問題(三)—— node啟動服務時listen監聽的端口被占用

Error: listen EADDRINUSE :::8888表示的就是listen監聽的端口被占用 查詢什么進程占用了8888端口 sudo fuser -n tcp 8888 &#xff08;指令一&#xff09; 或者 netstat -tln | grep 8888 &#xff08;指令二&#xff09;反復執行指令一&#xff0c;總得到不同結果&#x…

es6 --- 內置的Symbol值

Symbol.hasInstance // Symbol.hasInstance class MyClass {[Symbol.hasInstance] (foo) {return foo instanceof Array;} } [1, 2, 3] instanceof new MyClass() // true// symbol.hasInstance:會在[1, 2, 3] instanceof 時 自動調用 [Symbol.hasInstance] (foo) 方法... //…

對象的克隆

對象的克隆 1、克隆即復制的意思&#xff0c;對象的克隆&#xff0c;意味著生成一個對象&#xff0c;這個對象和某個對象的屬性和行為是一致的&#xff0c;但是這個對象和源對象是兩個不同的對象。實現對象的克隆&#xff0c;方法是實現Cloneable接口&#xff0c;否則會報異常C…

15 調試

1. pdb pdb是基于命令行的調試工具&#xff0c;非常類似gnu的gdb&#xff08;調試c/c&#xff09;。 def getAverage(a,b):result abprint("result is %s"%result)return resulta 10 b 20 c ab ret getAverage(a,b) print(ret) 2.執行時調試 程序啟動&#xff0…

html5播放視頻只有聲音不出現畫面?

一開始網上大神們都是要把MP4的編碼格式轉換成AVC&#xff08;H264&#xff09;&#xff0c;然后趕緊用格式工廠把它給換了&#xff0c;結果&#xff01;&#xff01; 沒用&#xff01;&#xff01;還是黑屏&#xff1f;&#xff1f;&#xff1f;咋回事啊&#xff0c;然后自己又…

vue項目代碼改進(一)login組件

Login登錄組件 1. 新增登錄頭像&#xff08;css樣式回顧&#xff09; 1&#xff09;div.avatar 2&#xff09;子絕父相定位&#xff0c;left…top… 3&#xff09;border 4&#xff09;placeholder 5&#xff09;box-shadow box-shadow: offset-x offset-y blur spread color …

es6 --- set實現并集(Union)、交集(Intersect)和差集(Difference)

Set:類似于數組,但是成員的值都是唯一的 let a new Set([1, 2, 3]); let b new Set([4, 3, 2]);// 并集 let union new Set([...a, ...b]);// 交集 let intersect new Set([...a].filter(x > b.has(x)));// 差級 let difference new Set( [...a].filter(x > !b.has…

解析DBF文件

上周&#xff0c;公司給了許多DBF后綴的數據文件讓我進行解析。 因為是DBF文件我發現mysql&#xff0c;和Oracle都能直接對DBF文件進行導入。在導入過程中發現這些數據庫并不能識別這些文件。 通過百度找到了打開這種文件的軟件Visual FoxPro、Access&#xff0c;用它們打開后出…

Scrum 沖刺 第一日

Scrum 沖刺 第一日 站立式會議燃盡圖Alpha 階段認領任務明日任務安排項目預期任務量成員貢獻值計算規則今日貢獻量參考資料站立式會議 返回目錄 燃盡圖 返回目錄 Alpha 階段認領任務 學號組員分工用時20162309邢天岳補充說明書&部分測試18h20162311張之睿編寫代碼20h201623…

淺析 NodeJs 的幾種文件路徑

Node 中的文件路徑大概有 __dirname, __filename, process.cwd(), ./ 或者 ../&#xff0c;前三個都是絕對路徑&#xff0c;為了便于比較&#xff0c;./ 和 ../ 我們通過 path.resolve(./)來轉換為絕對路徑。 先看一個簡單的栗子&#xff1a; 假如我們有這樣的文件結構&#xf…