django简单项目

    xiaoxiao2025-01-17  15

    1.建立简单后台管理项目(学员管理系统--基于django母版)

    2.包含三个子项项目(班级管理,学生管理,老师管理)

    3.子项目增删改查(基于pymysql原生sql)

    4.基于cookie的认证(基于装饰器)

    后台管理函数:

    from django.shortcuts import render,HttpResponse,redirect # Create your views here. import pymysql import json import time from functools import wraps from app01 import sqlhelper # 定义一个登入函数 def login(request): if request.method == "POST": uname = request.POST.get("username") passd = request.POST.get("password") obj = redirect("/class_list/") # 给浏览器写cookie,超时时间为60秒 obj.set_cookie("token","lph_login",max_age=60) return obj else: return render(request,"login.html") # 定义一个装饰器,给每个函数添加cookie验证 def check_login(fun): def inner(request): token = request.COOKIES.get("token") print("mytoken",token) if token: ret = fun(request) return ret else:return redirect("/login/") return inner # 班级管理函数 # class_list = check_login(class_list) @check_login def class_list(request): conn = pymysql.connect(host='192.168.1.124',port=3306,user='user1',password='123456',database='studentdb',charset='utf8') cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) sql = "select id,name from classes" cursor.execute(sql) ret_lst = cursor.fetchall() cursor.close() conn.close() print(ret_lst) return render(request,'class_lst.html',{'class_lst':ret_lst}) @check_login def add_class(request): name = request.POST.get('name') if name: conn = pymysql.connect(host='192.168.1.124',port=3306,user='user1',password='123456',database='studentdb',charset='utf8') cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) sql = "insert into classes(name) value(%s)" cursor.execute(sql,name) conn.commit() cursor.close() conn.close() return HttpResponse('1') else: return HttpResponse("班级名不能为空") @check_login def del_class(request): ret = {"state": True,"message": ""} del_id = request.POST.get("id") if del_id: print("data to delete id is",del_id) conn = pymysql.connect(host='192.168.1.124', port=3306, user='user1', password='123456', database='studentdb',charset='utf8') # cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) cursor = conn.cursor() sql = "delete from classes where id=%s" cursor.execute(sql, del_id) # 删除数据要commit conn.commit() cursor.close() conn.close() else: ret["state"] = False ret["message"] = "no such data to delete" ret = json.dumps(ret) # print(type(ret),ret) return HttpResponse(ret) @check_login def edit_class(request): ret = {"state": True, "message": ""} id = request.POST.get("id") name = request.POST.get("name") print(id,name) if id and name: conn = pymysql.connect(host='192.168.1.124', port=3306, user='user1', password='123456', database='studentdb',charset='utf8') cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) sql = "update classes set name=%s where id=%s" cursor.execute(sql,[name,id]) conn.commit() cursor.close() conn.close() else: ret["state"] = False ret["message"] = "要更新的数据不存在" ret = json.dumps(ret) return HttpResponse(ret) # 学生管理函数 @check_login def student_list(request): ret = sqlhelper.select_tb("select s.id,s.name as sname,c.id as cid,c.name as cname from students as s left join classes as c on s.class_id=c.id") class_list = sqlhelper.select_tb("select id,name from classes") return render(request,'student_lst.html',{"student_list":ret,"class_list":class_list}) # 添加学生函数 @check_login def add_student(request): ret = {"state":True,"message":""} name = request.POST.get("add_name") cid = request.POST.get("choice_cid") if name: sqlhelper.add_del_update_db("insert into students(name,class_id) values(%s,%s)",[name,cid]) else: ret["state"] = False ret["message"] = "用户名不能为空" return HttpResponse(json.dumps(ret)) @check_login def del_student(request): ret = {"state": True, "message": ""} id = request.POST.get("del_id") if id: sqlhelper.add_del_update_db("delete from students where id=%s",id) else: ret["state"] = False ret["message"] = "删除数据不成功" return HttpResponse(json.dumps(ret)) @check_login def edit_student(request): ret = {"state": True, "message": ""} id = request.POST.get("edit_id") name = request.POST.get("edit_name") cid = request.POST.get("class_id") print("id:",id,"name:",name,"cid",cid) if id and name: print("===========") sqlhelper.add_del_update_db("update students set name=%s,class_id=%s where id=%s",[name,cid,id]) else: ret["state"] = False ret["message"] = "删除数据不成功" return HttpResponse(json.dumps(ret)) # 老师管理函数 from app01 import sqlhelper sql = sqlhelper.Sqlhelper() @check_login def teacher_list(request): if request.method != "POST": if request.GET.get("getclasses") == "getclasses": classes = sql.select_all("select id,name from classes") return HttpResponse(json.dumps(classes)) teachers = sql.select_all("""select ct.id,t.id as tid,t.name as tname,c.id as cid,c.name as cname from class_teacher_relation as ct left join teachers as t on ct.teacher_id=t.id left join classes as c on ct.class_id=c.id;""") teachers_dic = {} for line in teachers: if line["tid"] in teachers_dic: teachers_dic[line["tid"]]["cnames"].append(line["cname"]) else: teachers_dic[line["tid"]] = {"id": line["id"], "tid": line["tid"], "tname": line["tname"], "cid": line["cid"],"cnames": [line["cname"]]} return render(request,'teacher_lst.html',{"teacher_dic":teachers_dic.values()}) else: pass @check_login def add_teacher(request): # 获取新增人员的名称 name = request.POST.get("name") # 在老师表中新增人员,并获取其id值 last_id = sql.insert_one("insert into teachers(name) VALUES(%s)",name) # 获取列表使用getlist方法 class_lst = request.POST.getlist("class_list") print(name, class_lst) # 组装参数 datas = [(int(cid),last_id) for cid in class_lst] print(datas) # 在老师班级关系表中插入新增人员关系数据 sql.insert_all("insert into class_teacher_relation(class_id,teacher_id) values(%s,%s)",datas) # sql.closeDB() return HttpResponse("ok") @check_login def del_teacher(request): # 获取要删除的行的id delID = int(request.POST.get("delID")) # 先删除老师班级关系表中的记录 sql.delete("delete from class_teacher_relation where teacher_id=%s",delID) # 再删除老师表中数据 sql.delete("delete from teachers where id=%s",delID) return HttpResponse("ok") @check_login def edit_teacher(request): if request.POST.get("editID"): editID = request.POST.get("editID") print(editID) # 获取待编辑ID所对应的班级 classID = sql.select_all("select id from classes where id in (select class_id from class_teacher_relation where teacher_id=%s)",editID) classID = [v["id"] for v in classID] print(classID) # 获取所有的班级 classes = sql.select_all("select id,name from classes") ret = [classID,classes] return HttpResponse(json.dumps(ret)) else: eid = request.POST.get("eID") name = request.POST.get("editname") newClsID = request.POST.getlist("class_id") print(eid,name,newClsID) # 修改老师表中的数据 sql.update("update teachers set name=%s where id=%s",[name,eid]) # 删除关系表中的数据 sql.delete("delete from class_teacher_relation where teacher_id=%s",eid) # 重新插入新的关系数据 datas = [(int(cid),int(eid)) for cid in newClsID] print(datas) sql.insert_all("insert into class_teacher_relation(class_id,teacher_id) values(%s,%s)",datas) return HttpResponse("ok") # 定义一个后台管理函数 @check_login def stuadmin(request): return render(request,"stuadmin.html") def test(request): return render(request,"test.html")

    后台管理母板:

    <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>后台管理页面</title> {#http://fontawesome.dashgame.com/ 图标选择地址#} <link rel="stylesheet" href="/static/font-awesome-4.7.0/font-awesome-4.7.0/css/font-awesome.min.css"/> <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.min.css/"/> <style> body { margin: 0px; } .pg-header { {#定义导航条高度和背景颜色#} height: 48px; background-color: #2b669a; {#让logo模块上下居中#} line-height: 48px; } .left { float: left; } .right { float: right; } .manul { position: absolute; top: 48px; left: 0px; bottom: 0px; width: 200px; background-color: #28a4c9; } .content { position: absolute; top: 48px; right: 0px; left: 200px; bottom: 0px; background-color: white; {#內容超出一页可显示的时候出现滚动条#} overflow: auto; } .pg-header .logo { color: white; font-size: 18px; width: 200px; text-align: center; border-right: 1px solid white; } .pg-header .info a { display: inline-block; padding: 0 15px; color: white; } .pg-header .info a:hover { background-color: #8c8c8c; } .header { padding: 0 15px; } .header img { position: relative; } .header .userinfo { display: none; position: absolute; top: 48px; width: 200px; right: 20px; background-color: #8c8c8c; z-index: 100; } .header:hover .userinfo { display: block; } .manul a { display: block; padding: 10px 5px; color: white; border-bottom: 1px solid white; text-align: center; } </style> </head> <body> <div class="pg-header"> <div class="logo left">学员后台管理</div> <div class="header right"> <img style="width: 48px;height: 48px;border-radius: 50%" src="/static/image/header.jpg"/> <div class="userinfo"> <a style="color: white">个人资料</a> <a style="color: white">注销</a> </div> </div> <div class="info right"> <a><i class="fa fa-commenting" aria-hidden="true"></i> 消息</a> <a><i class="fa fa-envelope-o" aria-hidden="true"></i> 邮件</a> </div> </div> <div class="pg-body"> <div class="manul"> <a class="cls" href="/class_list/"><i class="fa fa-plus-square" aria-hidden="true"></i> 班级管理</a> <a class="stu" href="/student_list/"><i class="fa fa-plus-square" aria-hidden="true"></i> 学生管理</a> <a class="tea" href="/teacher_list/"><i class="fa fa-plus-square" aria-hidden="true"></i> 老师管理</a> </div> <div class="content"> <ol class="breadcrumb"> <li><a href="#">首页</a></li> <li><a class="t1" href="#">班级管理</a></li> <li class="active t2">添加班级</li> </ol> {% block class %} {% endblock %} <nav aria-label="Page navigation"> <ul class="pagination"> <li> <a href="#" aria-label="Previous"> <span aria-hidden="true">«</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">»</span> </a> </li> </ul> </nav> </div> </div> </body> </html>

    班级管理页面

    {% extends "stuadmin.html" %} {% block class %} <title>班级展示页</title> <style> .hide { display: none; } .bk { position: fixed; left: 0; top: 0; right: 0; bottom: 0; background-color: black; opacity: 0.4; z-index: 998; } .model { position: fixed; left: 50%; top: 50%; width: 400px; height: 300px; margin-left: -200px; margin-top: -150px; background-color: white; z-index: 999; } </style> <!-- 添加模态框 --> <button type="button" class="btn btn-primary btn-sm" data-toggle="modal" data-target="#addModal" data-whatever="@mdo"> 添加 </button> <div id="addModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="gridSystemModalLabel"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span> </button> <h4 class="modal-title" id="gridSystemModalLabel">添加班级</h4> </div> <div class="modal-body"> <div class="input-group input-group-lg"> <span class="input-group-addon" id="sizing-addon1">请输入班级名</span> <input type="text" class="username form-control" name="name" placeholder="Username" aria-describedby="sizing-addon1"><span class="error" style="color: red"></span> </div> {# 给提交按钮绑定点击事件,发生点击则执行AjaxSend函数#} {# <input type="button" value="提交" onclick="editAjax();"/>#} </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">取消</button> {# 给提交按钮绑定点击事件,发生点击则执行AjaxSend函数#} <button type="button" class="btn btn-primary" onclick="AjaxSend();">提交</button> </div> </div><!-- /.modal-content --> </div><!-- /.modal-dialog --> </div><!-- /.modal --> <!-- 添加模态框 --> <!-- 编辑模态框 --> <div id="editModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="gridSystemModalLabel"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span> </button> <h4 class="modal-title" id="gridSystemModalLabel">编辑班级</h4> </div> <div class="modal-body"> <input class="edit_id" type="text" name="id" style="display: none"/> <div class="input-group input-group-lg"> <span class="input-group-addon" id="sizing-addon1">请编辑班级名</span> <input type="text" class="edit_class form-control" name="name" placeholder="Username" aria-describedby="sizing-addon1"><span class="error" style="color: red"></span> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">取消</button> {# 给提交按钮绑定点击事件,发生点击则执行editAjax函数#} <button type="button" class="btn btn-primary" onclick="editAjax();">提交</button> </div> </div><!-- /.modal-content --> </div><!-- /.modal-dialog --> </div><!-- /.modal --> <!-- 编辑模态框 --> <table class="table table-hover table-striped table-bordered table-condensed" border="1"> <thead> <tr> <th>ID</th> <th>班级名</th> <th>操作</th> </tr> </thead> <tbody> {% for row in class_lst %} <tr> <td>{{ forloop.counter }}</td> <td style="display: none">{{ row.id }}</td> <td>{{ row.name }}</td> <td><a class="btn btn-danger btn-sm" onclick="delAjax(this);"><i class="fa fa-trash-o" aria-hidden="true"></i> 删除</a> <button type="button" class="edit btn btn-info btn-sm" data-toggle="modal" data-target="#editModal" data-whatever="@mdo" onclick="ShowModel(this);"><i class="fa fa-pencil-square-o" aria-hidden="true"></i> 编辑 </button> </td> </tr> {% endfor %} </tbody> </table> {#<a href="http://www.baidu.com" onclick="return func()" style="display: none">我是绑定自定义事件的a标签</a>#} <script src="/static/jquery-3.3.1.min.js"></script> <script src="/static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script> <script> {#取消a标签默认事件操作#} function func() { alert("取消默认跳转/刷新页面"); return false } function ShowModel(ths) { {#获取编辑同行的所有数据#} var row_list = $(ths).parent().prevAll(); console.log(row_list); {#获取当前编辑行的数据id值#} var id = $(row_list[1]).text(); {#获取当前编辑行班级名#} var content = $(row_list[0]).text(); console.log("ShowModel:", id, content); {#将ID值填充id输入框#} $(".edit_id").val(id); $(".edit_class").val(content); } function AjaxSend() { $.ajax({ {#指定数据发送的目的url#} url: '/add_class/', {#指定提交数据的方式#} type: 'POST', {#要发送的数据#} data: {'name': $(".username").val()}, success: function (ret) { //当服务端处理完成后自动调用此函数,ret是服务端返回的值 if (ret === '1') { {#console.log('ok');#} {#location.href 跳转到指定页面#} location.href = '/class_list/'; } else { $(".error").text(ret); } } }) } function delAjax(arg) { {#获取当前标签的父标签--$(arg)是当前标签#} row = $(arg).parent(); {#console.log(row);#} {#获取当前标签前面的所有标签--row是DOM对象,$(row)转化为jquerry对象#} row_list = $(row).prevAll(); {#console.log(row_list);#} {#row_list[0]是班级名,row_list[1]是id#} {#将ID通过Ajax发到后端#} $.ajax({ url: "/del_class/", type: "POST", {#获取id值,并通过Ajax发往后端#} data: {"id": $(row_list[1]).text()}, success(ret) { console.log(ret); ret = JSON.parse(ret); if (ret.state) { {#刷新当前页面#} location.reload(); } else { alert(ret.message); } } }) } function editAjax(arg) { var edit_id = $('.edit_id').val(); var edit_class = $('.edit_class').val(); console.log(edit_id, edit_class); $.ajax({ url: '/edit_class/', type: 'POST', data: {'id': edit_id, 'name': edit_class}, success(ret) { console.log(ret); ret = JSON.parse(ret); if (ret.state) { {#如果返回成功码,则刷新页面#} location.reload(); } else { alert(ret.message); } } }) } </script> {% endblock %}

    学生管理页面:

    {% extends "stuadmin.html" %} <!-- 模态框相关样式 --> <style> .hide { display: none; } .bk { position: fixed; top: 0px; left: 0px; bottom: 0px; right: 0px; background-color: black; opacity: 0.4; z-index: 998; } .md { position: fixed; top: 50%; left: 50%; width: 400px; height: 300px; margin-left: -200px; margin-top: -150px; background-color: white; z-index: 999; } </style> <!-- 模态框相关样式 --> {% block class %} <!-- 添加模态框页面 --> <div class="add bk hide"></div> <div class="add md hide"> <label>请输入用户名: <input class="add_name" type="text"/> </label> <br/><br/><br/> <label>请选择班级: <select class="addChoiceID"> {% for row in class_list %} <option value="{{ row.id }}">{{ row.name }}</option> {% endfor %} </select> </label> <br/><br/><br/> <input class="add_yes" type="button" value="提交"/> <input class="add_no" type="button" value="取消"/> <span class="add_err"></span> </div> <!-- 添加模态框页面 --> <!-- 编辑模态框页面 --> <div class="edit bk hide"></div> <div class="edit md hide"> <label>请编辑用户名: <input class="edit_name" type="text"/> </label> <br/><br/><br/> <label>请选择班级: <select class="editChoiceID"> {% for row in class_list %} <option value="{{ row.id }}">{{ row.name }}</option> {% endfor %} </select> </label> <input class="edit_yes" type="button" value="提交"/> <input class="edit_no" type="button" value="取消"/> <span class="edit_err"></span> </div> <!-- 编辑模态框页面 --> <!-- 学生信息展示 --> <div style="margin: 5px 5px"> <input class="add_bt btn btn-primary btn-sm" type="button" value="添加"/> </div> <table class="table table-hover table-striped table-bordered table-condensed" border="1"> <thead> <tr> <th>ID</th> <th>名称</th> <th>班级</th> <th>操作</th> </tr> </thead> <tbody> {% for row in student_list %} <tr> <td>{{ forloop.counter }}</td> <td Id="{{ row.id }}">{{ row.sname }}</td> <td Cid="{{ row.cid }}">{{ row.cname }}</td> <td><a class="del_a btn btn-danger btn-sm"><i class="fa fa-trash-o" aria-hidden="true"></i> 删除</a> <a class="edit_a btn btn-info btn-sm"><i class="fa fa-pencil-square-o" aria-hidden="true"></i> 编辑</a></td> </tr> {% endfor %} </tbody> </table> <p class="del_err"></p> <!-- 学生信息展示 --> <!-- 引入jquery --> <script src="/static/jquery-3.3.1.min.js"></script> <!-- 引入jquery --> <!-- 绑定事件 --> <script> $(function () { <!-- 给add_bt类(添加按钮)绑定点击事件 --> $(".add_bt").click(function () { <!-- 添加按钮发生点击事件后执行的操作(显示模态框) --> $(".add").removeClass("hide"); }); <!-- 给add_no类(取消按钮)绑定点击事件 --> $(".add_no").click(function () { <!-- 取消按钮发生点击事件后执行的操作(取消模态框) --> $(".bk,.md").addClass("hide"); }); <!-- 给提交按钮绑定点击事件,发生点击事件则使用Ajax向后端提交数据 --> $(".add_yes").click(function () { $.ajax({ url:"/add_student/", type:"POST", data:{"add_name":$(".add_name").val(),"choice_cid":$(".addChoiceID").val()}, success(ret){ var ret = JSON.parse(ret); if(ret){ location.reload(); }else{ $(".add_err").val(ret.message); } }; }) }); <!-- 给del_a类(删除)绑定点击事件 --> $(".del_a").click(function () { <!-- 获取当前删除行的数据id值 --> var del_id = $($(this).parent().prevAll()[1]).attr("Id"); <!-- 数据发送到后端 --> $.ajax({ url: "/del_student/", type: "POST", data: {"del_id":del_id}, success(ret){ var ret = JSON.parse(ret); if(ret){ location.reload(); }else{ $(".del_err").text(ret.message); } } }) }) <!-- 给edit_a类(编辑)绑定点击事件 --> $(".edit_a").click(function () { $(".edit").removeClass("hide"); $Eles = $(this).parent().prevAll(); console.log($Eles); var content = $($Eles[1]).text(); var id = $($Eles[1]).attr("Id"); var cid = $($Eles[0]).attr("Cid"); console.log("====",id,content,cid); $(".edit_name").val(content); $(".edit_name").attr("editId",id); {#给select标签设置value值表示选中#} $(".editChoiceID").val(cid); }); <!-- 给编辑的提交按钮绑定事件 --> $(".edit_yes").click(function () { {#获取名称输入框的內容#} var content = $(".edit_name").val(); {#获取编辑行的ID值#} var edit_id = $(".edit_name").attr("editId"); {#获取class_id#} var class_id = $(".editChoiceID").val(); console.log(edit_id,content,class_id); $.ajax({ url:"/edit_student/", type:"POST", data:{"edit_id":edit_id,"edit_name":content,"class_id":class_id}, {#如果返回值是JSON格式,则指定数据类型,默认进行字符串反序列化#} dataType:"JSON", success(ret){ if(ret.state){ location.reload(); }else{ $(".edit_err").val(ret.message); } } }) }); <!-- 给编辑框的取消按钮绑定事件 --> $(".edit_no").click(function () { location.reload(); }) {#$(".edit_name").val($(this).parent().prev().val());#} {# var edit_id = $(this).parent().prev().attr("Id");#} {# $.ajax({#} {# url:"/edit_teacher/",#} {# type:"POST",#} {# data:{"edit_id":edit_id,"edit_name":$(".edit_name").val()},#} {# success(ret){#} {# console.log(ret);#} {# ret = JSON.parse(ret);#} {# if(ret){#} {# location.reload();#} {# }else{#} {# $(".edit_err").text(ret.message);#} {# }#} {# }#} {# })#} }) </script> <!-- 绑定事件 --> {% endblock %}

    老师管理页面:

    {% extends "stuadmin.html" %} <style> .bk { position: fixed; top: 0px; left: 0px; bottom: 0px; right: 0px; background-color: black; opacity: 0.4; z-index: 998; } .md { position: fixed; width: 400px; height: 300px; top: 50%; left: 50%; margin-top: -150px; margin-left: -200px; background-color: white; z-index: 999; } .hide { display: none; } </style> {% block class %} <div style="margin: 5px 5px"> <button class="addbtn btn btn-primary btn-sm">添加</button> </div> <!-- 添加模态框 --> <div class="add bk hide"></div> <div class="add md hide"> <label>请输入用户名: <input class="addinp" name="addname"/> </label> <br/><br/> <label>请选择班级: <select class="addclasslst" name="addclasslst" multiple> </select> </label> <button class="addyes">提交</button> <button class="addno">取消</button> </div> <!-- 添加模态框 --> <div class="edit bk hide"></div> <div class="edit md hide"> <label>请编辑用户名: <input class="editinp" name="editname"/> </label> <br/><br/> <label>请选择班级: <select class="editclasslst" name="editclasslst" multiple> </select> </label> <button class="edityes">提交</button> <button class="editno">取消</button> </div> <!-- 编辑模态框 --> <!-- 编辑模态框 --> <table class="table table-hover table-striped table-bordered table-condensed" border="1"> <thead> <tr> <th>ID</th> <th>老师名称</th> <th>任课班级</th> <th>操作</th> </tr> </thead> <tbody> {% for row in teacher_dic %} <tr> <td>{{ forloop.counter }}</td> <td tid="{{ row.tid }}">{{ row.tname }}</td> <td> {% for i in row.cnames %} <span style="display: inline-block;padding: 5px;border: 1px solid red">{{ i }}</span> {% endfor %} </td> <td><a class="delbtn btn btn-danger btn-sm"><i class="fa fa-trash-o" aria-hidden="true"></i> 删除</a> <a class="editbtn btn btn-info btn-sm"><i class="fa fa-trash-o" aria-hidden="true"></i> 编辑</a></td> </tr> {% endfor %} </tbody> </table> <script src="/static/jquery-3.3.1.min.js"></script> <script> $(document).ready(function () { {#给添加按钮绑定事件,显示对话框#} $(".addbtn").click(function () { $(".add").removeClass("hide"); {#点击添加按钮,先去获取所有班级列表#} $.ajax({ url:"/teacher_list/", type:"GET", data:{"getclasses":"getclasses"}, dataType:"JSON", success(ret){ {#动态添加标签,将班级信息填写到下拉选择框里#} for(var i=0;i<ret.length;i++){ {#console.log(ret[i].id,ret[i].name);#} var Ele = document.createElement("option"); Ele.innerText = ret[i].name; Ele.setAttribute("value",ret[i].id); $(".addclasslst").append(Ele); } } }) }); {#给添加提交按钮绑定事件,发送数据到后端#} $(".addyes").click(function () { var name = $(".addinp").val(); {#val函数遇到列表获取的则是列表#} var class_lst = $(".addclasslst").val(); console.log(name,class_lst); {#将数据发送到后台#} $.ajax({ url:"/add_teacher/", type: "POST", data: {"name":name,"class_list":class_lst}, {#如果提交的数据有列表,则要添加以下属性#} traditional:true, success(ret){ console.log(ret); if(ret === "ok"){ location.reload(); } } }) }); {#给添加取消按钮绑定事件,隐藏对话框#} $(".addno").click(function () { $(".add").addClass("hide"); }); {#给删除按钮绑定事件#} $(".delbtn").click(function () { {#获取所有当前td之前的td标签#} $Eles = $(this).parent().prevAll(); console.log($Eles[1]); {#获取要删除的行的id#} delID = $Eles[1].getAttribute("tid"); console.log(delID); {#将要删除的id发送给后端#} $.ajax({ url:"/del_teacher/", type:"POSt", data:{"delID":delID}, success(ret){ if(ret==="ok"){ location.reload(); } } }) }); {#给编辑按钮绑定事件#} $(".editbtn").click(function () { {#让模态框显示出来#} $(".edit").removeClass("hide"); {#获取编辑行的id值#} $Eles = $(this).parent().prevAll(); console.log($Eles); var editID = $Eles[1].getAttribute("tid"); console.log(editID); {#将编辑行的老师名填充到编辑框中#} $(".editinp").val($($Eles[1]).text()); {#给人员名称的input添加tid属性#} $(".editinp").attr("tid",editID); {#将编辑ID发送到后端获取到相关数据填写到模态框中#} $.ajax({ url:"/edit_teacher/", type:"POST", data:{"editID":editID}, dataType:"JSON", success(ret){ for(var i=0;i<ret[1].length;i++){ {#动态添加标签,将班级信息填写到下拉选择框里#} {#console.log(ret[i].id,ret[i].name);#} var Ele = document.createElement("option"); Ele.innerText = ret[1][i].name; Ele.setAttribute("value",ret[1][i].id); if(ret[0].indexOf(ret[1][i].id) != -1){ Ele.setAttribute("selected","selected"); } $(".editclasslst").append(Ele); } } }) }); {#给编辑取消按钮绑定事件,隐藏对话框#} $(".editno").click(function () { $(".edit").addClass("hide"); }); {#给编辑提交按钮绑定事件#} $(".edityes").click(function () { {#获取编辑的人员名称于id和名称#} var eID = $(".editinp").attr("tid"); var editname = $(".editinp").val(); {#获取编辑的班级id#} var class_id= $(".editclasslst").val(); {#将数据发送到后端#} $.ajax({ url:"/edit_teacher/", type:"POST", {#class_id 数据类型是列表,所以要加以下参数#} traditional:true, data:{"eID":eID,"editname":editname,"class_id":class_id}, success(ret){ if(ret === "ok"){ location.reload(); } } }) }) }) </script> {% endblock %}

    原生sql函数:

    import pymysql def select_tb(sql): conn = pymysql.connect(host='192.168.1.124',port=3306,user='user1',password='123456',database='studentdb',charset='utf8') cursor = conn.cursor(pymysql.cursors.DictCursor) cursor.execute(sql) ret = cursor.fetchall() cursor.close() conn.close() return ret def add_del_update_db(sql,arg): conn = pymysql.connect(host='192.168.1.124', port=3306, user='user1', password='123456', database='studentdb',charset='utf8') cursor = conn.cursor(pymysql.cursors.DictCursor) cursor.execute(sql,arg) conn.commit() cursor.close() conn.close() # 面向对象方式重写sqlhelper class Sqlhelper: # def __init__(self): # self.conn = pymysql.connect(host='192.168.1.124', port=3306, user='user1', password='123456', database='studentdb',charset='utf8') # self.cursor = self.conn.cursor(pymysql.cursors.DictCursor) # 定义连接数据库函数 def connect(self): self.conn = pymysql.connect(host='192.168.1.124', port=3306, user='user1', password='123456',database='studentdb', charset='utf8') self.cursor = self.conn.cursor(pymysql.cursors.DictCursor) # 定义提交函数 def commit(self): self.conn.commit() # 定义关闭数据库连接函数 def closeDB(self): self.cursor.close() self.conn.close() # 定义查询一条数据函数 def select_one(self,sql,args=None): self.connect() if args: self.cursor.execute(sql,args) else: self.cursor.execute(sql) ret = self.cursor.fetchone() self.closeDB() return ret # 定义查询多条数据函数 def select_all(self,sql,args=None): self.connect() if args: self.cursor.execute(sql,args) else: self.cursor.execute(sql) ret = self.cursor.fetchall() self.closeDB() return ret # 定义一个插入单行数据函数 def insert_one(self,sql,args=None): self.connect() if args: self.cursor.execute(sql,args) else: self.cursor.execute(sql) lastID = self.cursor.lastrowid self.commit() self.closeDB() return lastID # 定义一个插入多行数据函数 def insert_all(self,sql,args=None): self.connect() # args数据格式为[(1,v1),(2,v2),....] self.cursor.executemany(sql,args) self.commit() self.closeDB() # 定义一个删除行的函数 def delete(self,sql,args=None): self.connect() if args: self.cursor.execute(sql,args) else: self.cursor.execute(sql) self.commit() self.closeDB() # 定义一个修改数据的函数 def update(self,sql,args=None): self.connect() if args: self.cursor.execute(sql,args) else: self.cursor.execute(sql) self.commit() self.closeDB()

     

    最新回复(0)