一对多:1对多操作需要 select标签限制数据(因为有表中有 外键关系)
前端:
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta harset="UTF-8"> 5 <title>模态对话框</title> 6 <script src="/static/zhanggen.js"></script> 7 </head> 8 <body> 9 <style> 10 td{text-align: center;width:80px;height: 60px} 11 .shadow{position: fixed;left: 0;right: 0;bottom: 0;top: 0;background-color:silver;z-index: 999;opacity: 0.4 } 12 .add_modal{position: fixed;width: 250px;height: 225px; margin-top:30px;margin-left:520px;background-color:white;z-index: 1000} 13 .haid{display: none} 14 .del_modal{width: 150px;height:150px;z-index:1000;margin-left: 300px;position: fixed;left: 240px;top: 150px;text-align: center } 15 .edit_modal{width: 300px;height:330px;background-color: silver;position:fixed;left: 240px;top:150px;text-align: center} 16 17 </style> 18 <table border="1" style="border:none"> 19 <tr> 20 <td>学号</td> 21 <td>姓名</td> 22 <td>班级</td> 23 <td colspan="3">模态对话框操作</td> 24 </tr> 25 26 {% for row in list %} 27 </tr> 28 <td>{{ row.id }}</td> 29 <td>{{ row.name }}</td> 30 <td>{{ row.title }}</td> 31 <td><a href="#" onclick="show_modal(this)">添加</a></td> 32 <td id="del_s"><a href="#" onclick="modal_del(this)">删除</a> </td> 33 <td><a href="#"onclick="modal_edit(this)">编辑</a></td> 34 </tr> 35 36 {% endfor %} 37 38 {#模态对话框的对遮罩层#} 39 <div class="shadow haid" id="s"></div> 40 41 {#增加的模特对话框#} 42 <div class="add_modal haid" id="m"> 43 <p>所属班级: 44 <select id="66"> 45 </select> 46 </p> 47 <p>姓名:<input type="text" id="name7"></p> 48 <div id="flage" style="color: red"></div> 49 <p><input id="77" type="button"value="提交"></p> 50 <p><input id="cancel" type="button"value="取消" onclick="cancel()"></p> 51 </div> 52 </table> 53 54 {#删除的模态对话框#} 55 <div id="del" class="del_modal haid"style="background-color:gray"> 56 <p>真的要删除吗?</p> 57 <input id="y" style= "float: left; padding-left:10px;padding-right: 10px " type="button" value="确定"> 58 <input id="n" style=" float: right;padding-left: 10px;padding-right: 10px" type="button" value="取消"> 59 </div> 60 61 62 {#编辑的模态对话框#} 63 <div style="border: none" id="edit_mod" class="haid edit_modal"> 64 <p class="haid">ID:<input type="text" id="I"></p> 65 <p>姓名:<input type="text" id="N"></p> 66 <p style="margin-left:10px">所属班级 67 <select name="w" id="1993"> 68 </select> 69 </p> 70 <input id="1987" type="button" value="提交"> 71 <input type="button" value="取消" onclick="cancel()"> 72 </div> 73 74 </body> 75 76 77 78 79 <script> 80 {# 添加操作,触发的模态对话框#} 81 function show_modal(self) { 82 document.getElementById("s").classList.remove("haid") 83 document.getElementById("m").classList.remove("haid") 84 $.ajax({ 85 url:"/modal_add/", 86 type:"POST", 87 data:{"request":"give_class" }, 88 success:function(data){ 89 $('#66').html(data) }}) 90 ele777=document.getElementById("77") 91 ele777.onclick=function () { 92 $.ajax({ 93 url:'/modal_add/', 94 type:"POST", 95 data:{"name":$("#name7").val(),"cid": $('#66').val()}, 96 success:function (data) { 97 if(data=="xxoo"){location.href="/modal/"} 98 else{($('#flage').text("用户名/密码错误"))} 99 }})}} 100 101 {# 取消按钮触发的事件 #} 102 function cancel() { 103 location.href="/modal/" 104 } 105 106 {#删除操作 触发 模态对话框的 确认按钮 onclick事件 进而触发 ajanx请求服务端 #} 107 function modal_del(self) { 108 id1=$(self).parent().siblings().eq(0).text(); 109 $("#del").removeClass("haid"); 110 ele=document.getElementById("y"); 111 ele.onclick=function () { 112 $.ajax({ 113 url: '/modal_del/', 114 type: 'POST', 115 data:{"id":id1}, 116 success:function (data) { 117 if (data == "OK"){location.href="/modal/"} 118 }})} 119 ele1=document.getElementById("n"); 120 ele1.onclick=function () {location.href="/modal/"} } 121 122 function modal_edit(self) { 123 id=$(self).parent().siblings().eq(0).text(); 124 name=$(self).parent().siblings().eq(1).text(); 125 cid=$(self).parent().siblings().eq(2).text(); 126 $("#edit_mod").removeClass("haid"); 127 $('#I').val(id) 128 $('#N').val(name) 129 $.ajax({ 130 url:'/modal_edit/', 131 type:"POST", 132 data:{"id":id}, 133 success:function(data){ $("#1993").html(data); 134 $('#edit_mod').removeClass("haid")}}) 135 {# 给编辑对话栏的提交按钮动态添加事件#} 136 ele=document.getElementById("1987"); 137 ele.onclick=function () { console.log("ok") 138 $.ajax({ 139 url:'/modal_edit/', 140 type:"GET", 141 data:{"id":($('#I').val()),"name":$('#N').val(),"class_id":$("#1993").val()}, 142 success:function(data){ 143 console.log(data) 144 if (data=='ok') 145 {location.href="/modal/"}}})} 146 } 147 148 </script> 149 150 </html>
逻辑:
1 from django.shortcuts import HttpResponse,render,redirect 2 from until import mysqlhelper 3 sql="select day64.student.id,day64.student.`name`,day64.class.title from day64.student LEFT JOIN day64.class on day64.student.class_id=day64.class.id" 4 def modal(request): 5 res=mysqlhelper.get_list(sql) 6 return render(request,"modal.html",{"list":res}) 7 8 def modal_add(request): 9 if request.POST.get("request")=="give_class": 10 sql = "select * FROM day64.class" 11 res = mysqlhelper.get_list(sql) 12 html = "" 13 for i in res: 14 html += '<option id=%s value="%s">%s</option >' % (i.get("id"), i.get("id"), i.get("title")) 15 return HttpResponse(html) 16 else: 17 N1=request.POST.get("name") 18 if len(N1)==0: 19 return HttpResponse("x") 20 else: 21 D1=request.POST.get("cid") 22 sql="INSERT INTO day64.student(name,class_id) VALUES(%s,%s)" 23 mysqlhelper.moddify(sql,[N1,D1]) 24 return HttpResponse("xxoo") 25 26 def modal_del(request): 27 sid=request.POST.get("id") 28 mysqlhelper.moddify('delete from day64.student where id=%s',sid) 29 return HttpResponse("OK") 30 31 def modal_edit(request): 32 if request.method=='POST': 33 id1=request.POST.get("id") 34 res=mysqlhelper.get_one("SELECT class_id FROM student WHERE id=%s;",id1) 35 class_id=res.get('class_id') 36 sql="select * FROM day64.class" 37 res=mysqlhelper.get_list(sql) 38 html="" 39 for i in res: 40 if i.get("id")==class_id: 41 html += '<option id=%s value="%s"selected>%s</option >' % (i.get("id"),i.get("id"),i.get("title")) 42 else: 43 html+='<option id=%s value="%s">%s</option >'% (i.get("id"),i.get("id"),i.get("title")) 44 return HttpResponse(html) 45 else: 46 id3=request.GET.get("id") 47 name=request.GET.get("name") 48 cid=request.GET.get("class_id") 49 sql="UPDATE day64.student SET name=%s,class_id=%s WHERE id=%s" 50 mysqlhelper.moddify(sql,[name,cid,id3]) 51 return HttpResponse("ok")
1 import pymysql 2 def get_list(sql): 3 conn = pymysql.connect(host="192.168.182.128", user="eric", password="123123", database="day64", charset="utf8") 4 cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) 5 cursor.execute(sql) 6 res = cursor.fetchall() 7 cursor.close() 8 conn.close() 9 return res 10 11 12 def get_one(sql,args): 13 conn = pymysql.connect(host="192.168.182.128", user="eric", password="123123", database="day64", charset="utf8") 14 cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) 15 cursor.execute(sql,args) 16 res = cursor.fetchone() 17 cursor.close() 18 conn.close() 19 return res 20 21 def moddify(sql,args): 22 conn = pymysql.connect(host="192.168.182.128", user="eric", password="123123", database="day64", charset="utf8") 23 cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) 24 cursor.execute(sql,args) 25 conn.commit() 26 cursor.close() 27 conn.close()
基于面向对象数据库封装
class SqlHelper(object): def __init__(self): # 读取配置文件 self.connect() def connect(self): self.conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='s4db65', charset='utf8') self.cursor = self.conn.cursor(cursor=pymysql.cursors.DictCursor) def get_list(self,sql,args): self.cursor.execute(sql,args) result = self.cursor.fetchall() return result def get_one(self,sql,args): self.cursor.execute(sql,args) result = self.cursor.fetchone() return result def modify(self,sql,args): self.cursor.execute(sql,args) self.conn.commit() def multiple_modify(self,sql,args): # self.cursor.executemany('insert into bd(id,name)values(%s,%s)',[(1,'alex'),(2,'eric')]) self.cursor.executemany(sql,args) self.conn.commit() def create(self,sql,args): self.cursor.execute(sql,args) self.conn.commit() return self.cursor.lastrowid def close(self): self.cursor.close() self.conn.close()
多对多:A表 B表之间双向有外键关系; 双向1对多就是多对多; 一个老师教多个班级,一个班级有多个老师;
引申出第三张表:记录A表和B表的关系;
注意:多对多表之间有外键关系先删除 引用外键表中数据,没人引用了再删除外键!
def modal_del(request): tid=request.GET.get("tid") #有外键关系先删除 引用外键表中数据 mysqlhelper.moddify("DELETE FROM teacher_class WHERE tid=%s", [tid]) #没人引用了再 删除外键 mysqlhelper.moddify("DELETE FROM teacher WHERE id=%s",[tid]) return redirect('/modal/')
前端
主页
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>多对多</title> <script src="/static/zhanggen.js"></script> <style> .shadow{ position: fixed; left: 0; right: 0; top:0; bottom: 0; background-color: black; opacity: 0.8; z-index: 999; } .modal{ width: 400px; height: 300px; z-index: 1000; margin-left: 420px; margin-top: 50px; background-color:silver; } .haid{ display: none; } </style> </head> <body> <table cellspacing="15"> <th>ID</th><th>老师姓名</th><th>任教班级</th><th colspan="3">操作</th> {% for row in list %} <tr> <td>{{ row.tid }}</td> <td>{{ row.tname }}</td> <td> {% for ri in row.titles %} {{ri}} {% endfor %} </td> <td><a href="#" onclick="return add(this)">添加</a></td> <td><a href="/modal_edit/?tid={{row.tid }}"> 编辑</a></td> <td><a href="/modal_del/?tid={{ row.tid }}">删除</a> </tr> {% endfor %} </table> <div id="1" class="shadow haid "> <div class="modal"> <p>老师姓名:<input id="tname" type="text"></p> <p>任教班级: <select id="2" multiple="multiple"> {% for row in class_list %} <option value="{{ row.id }}">{{ row.title }}</option> {% endfor %} </select> </p> <input id="3" type="button" value="提交"> <input id="4" type="button" value="取消"> </div> </div> <script> function add(self) { $("#1").removeClass("haid") $('#4').click(function () { location.reload() }) $('#3').click(function () { class_id=$('#2').val() name=$("#tname").val() console.log(name=$("#tname").val()) $.ajax({ url:"/modal_add/", type:'POST', data:{"cid":class_id,"tname":name}, success:function(data){ if (data=='OK'){location.reload()}} }) }) return false } </script> </body> </html>
编辑
<!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.css"> <meta charset="UTF-8"> <title>编辑</title> </head> <body> <h1>编辑老师</h1> <form method="post" action="/modal_edit/?tid={{t_info.id }}"> <p>老师姓名:<input name="tname" type="text" value={{ t_info.name }}></p> <p>任教课程: <select name="class_id" multiple size="5"> {% for row in clas %} {% if row.id in cids%} <option selected value={{ row.id}}>{{ row.title}}</option> {%else%} <option value={{ row.id}}>{{ row.title}}</option> {% endif %} {% endfor %} </select> </p> <input class="btn btn-primary" type="submit" placeholder="提交"> <input type="button" onclick="cancle(this)" value="取消"> </form> </body> <script> function cancle(self) { location.href="/modal/" } </script> </html>
逻辑
from until import mysqlhelper from django.shortcuts import HttpResponse,render,redirect def modal(request): sql=''' SELECT teacher.id as tid,teacher.`name`as tname,class.title FROM day64.teacher LEFT JOIN teacher_class ON day64.teacher.id=day64.teacher_class.tid LEFT JOIN day64.class ON day64.teacher_class.cid=day64.class.id; ''' teacher_list= mysqlhelper.get_list(sql,[]) res={} for row in teacher_list: tid=row["tid"] if tid in res: res[tid]["titles"].append(row["title"]) else: res[tid]={'tid':row["tid"],'tname':row["tname"],'titles':[row["title"],]} class_list=mysqlhelper.get_list("SELECT id ,title FROM day64.class" ,[]) return render(request,'modal.html',{"list":res.values(),"class_list":class_list} ) def modal_add(request): ret = {"status":True, 'message': None} tname=request.POST.get('tname') class_ids=request.POST.getlist("cid[]") #['1', '2', '3', '4', '5'] tid=mysqlhelper.moddify("insert INTO day64.teacher (name) VALUES(%s)",[tname]) for i in class_ids: mysqlhelper.moddify("INSERT INTO teacher_class (tid,cid) VALUES(%s,%s)",[tid,i]) return HttpResponse("OK") def modal_edit(request): if request.method=='GET': tid=request.GET.get("tid") teacher_info=mysqlhelper.get_one("select id,name FROM day64.teacher WHERE id=%s",[tid]) print(teacher_info) class_id=mysqlhelper.get_list("select cid FROM teacher_class WHERE tid=%s",[tid]) print(class_id) classes=mysqlhelper.get_list('select * FROM class',[]) cids=[] for items in class_id: cids.append(items['cid']) return render(request,'edit.html',{"t_info":teacher_info,'cids':cids,'clas':classes}) else: print(request.POST) tid=request.GET.get("tid") class_list=request.POST.getlist('class_id') tname=request.POST.get('tname') # print(tid,class_list,tname) mysqlhelper.moddify("update teacher set name=%s WHERE id=%s",[tname,tid]) mysqlhelper.moddify("DELETE FROM teacher_class WHERE tid=%s",[tid]) for i in class_list: mysqlhelper.moddify("INSERT INTO teacher_class (tid,cid) VALUES(%s,%s)", [tid,i]) return redirect('/modal/') def modal_del(request): tid=request.GET.get("tid") #有外键关系先删除 引用外键表中数据 mysqlhelper.moddify("DELETE FROM teacher_class WHERE tid=%s", [tid]) #没人引用了再 删除外键 mysqlhelper.moddify("DELETE FROM teacher WHERE id=%s",[tid]) return redirect(
基于Django ORM
1、1对多
逻辑
from django.conf.urls import url from django.contrib import admin from app01 import views urlpatterns = [ url(r'^students.html',views.students), url(r'^student_add/',views.student_add), url(r'^student_del/(.*).html/',views.student_del), url(r'^student_edit/',views.student_edit), ]
from django.shortcuts import render,HttpResponse,reverse,redirect from app01 import models # Create your views here. def students(request): user_list=models.User_info.objects.all() return render(request,'students.html',{'name_list':user_list,"str":"1",'int':1}) def student_add(request): if request.method=="GET": groups=models.User_group.objects.all() return render(request,'student_add.html',{"groups":groups}) else: name=request.POST.get('name') age=request.POST.get('age') group=request.POST.get('group') models.User_info.objects.create(name=name,age=age,user_group_id=group) return redirect('/students.html/') def student_del(request,args1): # user_id=request.GET.get('id') models.User_info.objects.filter(id=args1).delete() return redirect('/students.html/') def student_edit(request): current_uid = request.GET.get('id') if request.method=='GET': user={} for row in models.User_info.objects.filter(id=current_uid) : user['id']=row.id user['name'] = row.name user['age'] = row.age user['gid']=row.user_group_id groups=models.User_group.objects.all() return render(request,'student_edit.html',{"users":user,'groups':groups}) else: name=request.POST.get('name') age=request.POST.get('age') gid=request.POST.get('group') uid=request.POST.get('id') models.User_info.objects.filter(id=uid).update(name=name,age=age,user_group_id=gid) return redirect('/students.html/')
模板
{% extends 'layout.html'%} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>学生管理系统</title> {% block css %} <style> .title td{color: cornflowerblue;font-size: 15px} </style> {%endblock css%} </head> <body> {% block xx %} <form method="post" action="#"> <table class="table table-hover"> <tr class="title"><td>姓名</td><td>年龄</td><td colspan="2">部门</td></tr> {% for row in name_list %} <tr> <td>{{ row.name }}</td> <td>{{ row.age }}</td> <td>{{ row.user_group.title }}</td> <td><a href="/student_edit/?id={{ row.id }}">编辑</a> <a href="/student_del/{{row.id}}.html/">删除</a></td> </tr> {% endfor %} </table> </form> {% endblock xx%} </body> {% block js %} {% endblock js %} </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>添加学生</title> </head> <body> <form METHOD="post" action="/student_add/"> <p><input name="name" type="text" placeholder="姓名"></p> <p> <input name="age" type="text" placeholder="年龄"></p> <p>部门 <select name="group" > {% for row in groups %} <option value="{{ row.id }}">{{row.title}}</option> {% endfor %} </select> </p> <input type="submit" placeholder="提交"> <input id="1" type="button"value="取消" onclick="canle(this)"> </form> </body> <script> function canle(self) {location.href="/students.html/"} </script> </html>
母版
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> <link rel="stylesheet" href="/static/plugins/bootstrap-3.3.7-dist/css/bootstrap.css"> <link rel="stylesheet" href="/static/plugins/font-awesome-4.7.0/css/font-awesome.css"> <link rel="stylesheet" href="/static/css/commons.css"> {% block css %}{% endblock %} </head> <body> <div class="pg-header"> <div class="logo left">后台管理</div> <div class="avatar right" style="position: relative"> <img style="width: 40px;height: 40px;" src="/static/images/1.jpg"> <div class="user-info"> <a>个人资料</a> <a>注销</a> </div> </div> <div class="rmenus right"> <a><i class="fa fa-commenting-o" 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="menus"> <a> <i class="fa fa-futbol-o" aria-hidden="true"></i> 班级管理</a> <a>学生管理</a> <a>班级管理</a> <a>老师管理</a> </div> <div class="content"> <ol class="breadcrumb"> <li><a href="#">首页</a></li> <li><a href="#">学生管理</a></li> <li><a class="ctive" href="/student_add/">添加用户</a></li> </ol> {% block xx %}{% endblock %} </div> </div> {% block js %}{% endblock %} </body> </html>
ORM数据库
from django.db import models # Create your models here. class User_group(models.Model): title=models.CharField(max_length=200,null=True) class User_info(models.Model): name=models.CharField(max_length=20,null=True) age = models.IntegerField(default=18) pwd=models.CharField(max_length=60,default="123.com") user_group=models.ForeignKey("User_group")
知识补充:
1、1对1单表操作: 当页面加载完了之后执行的 $(function () { }) JS:阻止默认事件的发生 <a id="1" href="#" onclick="return add(this)" <script> function add() { return true } </script> return false(阻止a标签跳转, 阻止form表单的提交提交 属于阻止默认事件 ) loaction reload 重新加载当前页面 JS反序列化:JOSN.parse(JS字符串)转JS对象 JS序列化:JSON.stringfy(对象)转字符串
Django服务端 定义return返回值,前端根据返回值,显示后端出现的异常;
后端
def modal_add(request): ret = {"status":True, 'message': None} try: tname=request.POST.get('tname') class_ids=request.POST.getlist("cid") #['1', '2', '3', '4', '5'] tid=mysqlhelper.moddify("insert INTO day64.teacher (name) VALUES(%s)",[tname]) for i in class_ids: mysqlhelper.moddify("INSERT INTO teacher_class (tid,cid) VALUES(%s,%s)",[tid,i]) except Exception as e: ret["status"] = False ret["message"]="异常" return HttpResponse(json.dumps(ret))
前端
success:function(data){
if (data.status==true){location.reload()}
else {alert(data.status);location.reload()}
}
Jquery绑定事件: $("#id").clik( function(){}) 2、1对多操作: $(funtion)当前页面HTML加载完了加载的 dataType:'JSON',把数据直接转换成JSON格式
traditional:true JS会把发送的列表数据做特殊处理,加了之后不会了;
2、样式:Bootstrap Bootstrap,来自 Twitter,是目前很受欢迎的前端框架。Bootstrap 是基于 HTML、CSS、JAVASCRIPT 的,它简洁灵活,使得 Web 开发更加快捷。 3、图标:font awesome 一套绝佳的图标、字体库和CSS框架 模板的渲染在后台执行: placeholder="老师姓名" input默认显示 加载框 traditional:ture 前端发送列表 直接发送列表