##MySQL数据准备
#班级表 create table classes( id int auto_increment primary key, name varchar(32) not null default '' )engine=Innodb charset=utf8; #学生表 create table student( id int auto_increment primary key, name varchar(32) not null default '', class_id int not null default 1, constraint fk_student_classes foreign key(class_id) references classes(id) )engine=Innodb charset=utf8; #教师表 create table teacher( id int auto_increment primary key, name varchar(32) not null default '' )engine=Innodb charset=utf8; #关联表 create table teacher2class( id int auto_increment primary key, t_id int not null default 1, c_id int not null default 1, constraint fk_teacher_classes1 foreign key(t_id) references teacher(id), constraint fk_classes foreign key(c_id) references classes(id) )engine=Innodb charset=utf8;
##数据库封装成类
为了提高数据库的操作速度,避免重复的进入和退出,我们可以把一些常用的数据库的操作封装成一个类。 把数据库操作写成函数:每次都得连接数据库一次连接一次提交,重复操作浪费时间 把数据库操作写成类:一次连接可以多次提交,最佳重复操作时不需要关闭数据库 import pymysql class Sqlmanager: def __init__(self): self.connect() #实例化后自动执行此函数 def connect(self):#此时进入数据库,游标也已经就绪 self.conn = pymysql.connect(host='127.0.0.1',port=3306,user='root',password='123',db='db58',charset='utf8') self.cursor = self.conn.cursor(cursor=pymysql.cursors.DictCursor) def get_all(self,sql,args=None): self.cursor.execute(sql,args) result = self.cursor.fetchall() return result def get_one(self,sql,args=None): self.cursor.execute(sql, args) result = self.cursor.fetchone() return result def add_num(self,sql,args=None): self.cursor.execute(sql, args) self.conn.commit() def del_num(self,sql,args=None): self.cursor.execute(sql,args) self.conn.commit() def up_num(self,sql,args=None): self.cursor.execute(sql, args) self.conn.commit()
##Django框架 单表操作细节(班级表和教师表)
#1、单表操作的内容
我们这里对数据库单表的操作包含增删改查四部分
具体链接数据库的方式我们是通过pymysql,当然你也可以用其他的
#2、两种方式的概念与区别
1、新url的方式
主要就是我们每一次向后台提交并访问数据时,后台都会给我们
跳转到一个新的界面,来完成我们的操作
2、模态对话框的方式
就是我们可以在页面不刷新的情况下,完成前后台数据之间的交互
两者最大的区别就是新url肯定会刷新页面,而模态框可以让页面不刷新进行交互
##新url方式
新url主要利用render和redirect对浏览器页面进行重新刷新,还有a标签进行页面跳转
{{}} :跟变量相关
{%%} :跟逻辑相关
前后端传递的变量(其实时字典中的key)要一致
a:相当于重新向
render:模板引擎渲染新页面
redirect:重定向跳到另一个页面
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> h,a{ margin: 0; padding: 0; text-decoration: none; } #hhh{ background-color: cyan; text-align: center; } #ttt{ 100%; text-align: center; background-color: cadetblue; } #a1{ height:100px ; 50px; } </style> <style> .shadow{ background-color: black; height: 1000px; position: fixed; top: 0; left: 0; right: 0; bottom: 0; opacity: 0.4; z-index: 99; display: none; } .content{ background-color: white; 500px; height: 300px; position: fixed; top:100px; left: 500px; z-index: 100; display: none; } #error{ color: red; } </style> </head> <body> <h1 id="hhh">教师信息</h1> <div> <table border="1px" id="ttt"> <thead> <tr> <th>ID</th> <th>教师名称</th> <th>操作</th> </tr> </thead> {% for item in teachers %} <tr> <td>{{ item.id }}</td> <td>{{ item.name }}</td> <td> {# a标签提交数据只能通过GET提交,所以删除或者更新我们想要携带数据只能通过?在后面进行拼接 #} <a href="/del_teacher/?id={{ item.id }}">删除|</a> <a href="/up_teacher/?id={{ item.id }}">更新</a> </td> </tr> {% endfor %} </table> </div> <div id="dd1"> {# <!--点击添加教师跳转到新url中去添加信息-->#} <a href="/add_teacher/" id="a1">添加教师</a> <button id="btn">模态对话框添加班级</button> </div> <div class="shadow"></div> <div class="content"> 教师名称:<input type="text" name="teachername" id="teachername"> <input type="button" value="提交" id="tijiao"> <input type="button" id="cancle" value="取消"> <spam id="error"></spam> </div> </body> <script src="../static/js/js/jquery-3.4.1.js"></script> <script> $('#btn').click(function () { {#$(".shadow").css('display','block');#} $(".shadow").show(); $(".content").show(); }); $('#cancle').click(function () { $(".shadow").css('display','none'); $(".shadow").hide(); $(".content").hide(); }); $('#tijiao').click(function () { $.ajax( { type:"POST", url:"/modal_add_teacher/", data:{"teachername":$('#teachername').val()}, success:function (data) { if(data == 'ok'){ alert('添加成功'); {#跳转#} window.location.href = '/teacher/' } else { alert('添加失败'); $('#error').text(data) } } } ) }) </script> </html>
"""mydjango58 URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url from django.contrib import admin from django.shortcuts import HttpResponse,render,redirect from mydjango58.sqlmanager import * def classes(request): # import pymysql # conn = pymysql.connect(host='127.0.0.1',user='root',password='123',db='db58',charset='utf8') # cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) # sql = 'select * from classes' # cursor.execute(sql) # classes = cursor.fetchall() # print(classes) sql="select * from classes" classes = Sqlmanager().get_all(sql) return render(request,'classes.html',{"classes":classes}) def add_class(request): if request.method == 'GET': return render(request,'add_class.html') else: classname = request.POST.get('classname') # print(classname) # import pymysql # conn = pymysql.connect(host='127.0.0.1', user='root', password='123', db='db58', charset='utf8') # cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) # sql = "insert into classes(name) values(%s)" # cursor.execute(sql,(classname,)) # conn.commit() sql="insert into classes(name) values(%s)" Sqlmanager().add_num(sql,(classname,)) return redirect('/classes/') def del_class(request): #删除要拿到删除班级id class_id = request.GET.get('id') # print(class_id) # import pymysql # conn = pymysql.connect(host='127.0.0.1', user='root', password='123', db='db58', charset='utf8') # cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) # sql = "delete from classes where id = %s" # cursor.execute(sql, (class_id,)) # conn.commit() sql = "delete from classes where id = %s" Sqlmanager().add_num(sql, (class_id,)) return redirect('/classes/') def up_class(request): if request.method == 'GET': id = request.GET.get('id') # import pymysql # conn = pymysql.connect(host='127.0.0.1', user='root', password='123', db='db58', charset='utf8') # cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) # sql = 'select * from classes where id = %s' # cursor.execute(sql, (id,)) # classes = cursor.fetchone() # print(classes) sql = 'select * from classes where id = %s' classes = Sqlmanager().get_one(sql, (id,)) return render(request, 'update_class.html', {"class_id": classes['id'], "classname": classes['name']}) else: classname =request.POST.get("classname") id =request.POST.get('class_id') # print(classname,id) # import pymysql # conn = pymysql.connect(host='127.0.0.1', user='root', password='123', db='db58', charset='utf8') # cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) # sql = 'update classes set name=%s where id = %s' # cursor.execute(sql, (classname,id)) # conn.commit() sql = 'update classes set name=%s where id = %s' Sqlmanager().up_num(sql,(classname,id)) return redirect('/classes/') def modal_add_class(request): classname = request.POST.get('classname') print(classname) if not classname: return HttpResponse('faild') else: # import pymysql # conn = pymysql.connect(host='127.0.0.1', user='root', password='123', db='db58', charset='utf8') # cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) # sql = "insert into classes(name) values(%s)" # cursor.execute(sql, (classname,)) # conn.commit() sql = "insert into classes(name) values(%s)" Sqlmanager().add_num(sql, (classname,)) return HttpResponse('ok') def teacher(request): sql = "select * from teacher" teachers = Sqlmanager().get_all(sql) return render(request, 'teachers.html', {"teachers": teachers}) def add_teacher(request): if request.method == 'GET': return render(request,'add_teacher.html') else: teachername = request.POST.get('teachername') sql = "insert into teacher(name) values(%s)" Sqlmanager().add_num(sql, (teachername,)) return redirect('/teacher/') def del_teacher(request): teacher_id = request.GET.get('id') sql = "delete from teacher where id=%s" Sqlmanager().del_num(sql,(teacher_id,)) return redirect('/teacher/') def up_teacher(request): if request.method == 'GET': id = request.GET.get('id') sql = 'select * from teacher where id = %s' teachers = Sqlmanager().get_one(sql, (id,)) print(teachers) return render(request, 'update_teacher.html', {"teacher_id": teachers['id'], "teachername": teachers['name']}) else: teachername =request.POST.get("teachername") id = request.POST.get('teacher_id') print(teachername,id) sql = 'update teacher set name=%s where id = %s' Sqlmanager().up_num(sql, (teachername, id)) return redirect('/teacher/') def modal_add_teacher(request): teachername = request.POST.get('teachername') print(teachername) if not teachername: return HttpResponse('faild') else: sql = "insert into teacher(name) values(%s)" Sqlmanager().add_num(sql, (teachername,)) return HttpResponse('ok') # 写好路由关系映射 urlpatterns = [ # url(r'^admin/', admin.site.urls), url(r'^classes/', classes), url(r'^add_class/', add_class), url(r'^modal_add_class/', modal_add_class), url(r'^del_class/', del_class), url(r'^up_class/', up_class), url(r'^teacher/',teacher), url(r'^add_teacher/',add_teacher), url(r'^modal_add_teacher/',modal_add_teacher), url(r'^del_teacher/',del_teacher), url(r'^up_teacher',up_teacher), ]
##模态对话框
#1、作用
主要通过ajax与后台进行信息之间的交互,保证页面不进行刷新
通过给特定标签绑定click事件,在事件中通过jq对象对页面进行一些简单的修改以及与后台的数据交互
#2、什么是模态框
网页上面新增了一个窗口,这也就是常见的模态框样式
#3、模态框结构
1、文本层
文本层就是原本的页面,他存在于三层图层最下面的一层
不用操作样式
2、阴影层
阴影层就是看着灰蒙蒙的那一层,位于三层图层中间的一层
我们需要把阴影层进行定位(fixed),让他盖在文本层之上
3、弹出框层
我们看到的和需要输入内容(完成信息的前后台交互)的一层就是弹出框层,
位于三层图层最上面一层,我们也需要把这一层进行定位(fixed),使他位于阴影层之上显示
注:既然阴影层和弹出框层都需要定位(fixed),那么谁显示在上面就需要根据z-index来确定
##ajax参数
$.ajax({ type: 'post', //向后台提交数据的方式 url: "/model_add_classes/", //提交给后台的url,因为这里是本站跳转,直接写uri就可以 data: {"classname": $('.classname').val()}, //data是向后台提交的数据,用字典的方式传送,后台通过key进行取值 //success是后台成功返回信息的情况,对应函数里的参数就是后台发送的数据 success: function (data) { if (data == 'ok') { //刷新页面通过 window.location.href = '/model_classes'; window.location.href = '/model_classes'; } else { $('.tips').text("用户名不能为空"); {#console.log(data);#} } ; }, });
##简单模态对话框代码
1.先写html代码 2.再写css样式 3.利用jquery代码绑定点击事件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>简易模态框</title> <style> /*我们先来把阴影层样式搞定,大小为全屏窗口,透明度调低一些,这样可以看到文本框的内容*/ .shadow{ 100vw; height: 100vh; background-color: black; opacity: 0.4; top: 0; left: 0; position: fixed; display: none; /*先让他不显示,然后我们点击按钮显示*/ z-index: 6; } /*弹出框层设置基本差不多,需要注意把z-index设的比阴影层高*/ .frame{ 300px; height: 300px; background-color: white; position: fixed; top: 200px; left: 400px; z-index: 66; display: none; /*先让他不显示,然后我们点击按钮显示*/ } </style> </head> <body> <!--这里我们就把body当成我们的文本层--> <h1>这是文本层</h1> <button type="button" class="show">点我弹出模态框</button> <!--再来创建阴影层--> <div class="shadow"></div> <!--创建弹出框层--> <div class="frame"> <span>这是弹出框层</span><br> <input type="text"> <input type="button" value="提交" class="submit"> <input type="button" value="取消" class="cancel"> </div> </body> <!--导入jquery--> <script src="http://code.jquery.com/jquery-1.12.4.js" integrity="sha256-Qw82+bXyGq6MydymqBxNPYTaUXXq7c8v3CwiYwLLNXU=" crossorigin="anonymous"></script> <script> //第一步,我们需要监视文本层的按钮,一点击我们就把模态框显示出来 $('.show').click(function () { $('.shadow').show(); $('.frame').show(); }); //第二步,我们需要监视弹出框层的取消按钮,一点击就把模态框隐藏起来 $('.cancel').click(function () { $('.shadow').hide(); $('.frame').hide(); }); //到此位置,简易模态框就完成了 </script> </html>