Web开发
Flask
Flask框架为了方便书写标签,用户把返回给浏览器的字符串写入到文件里,再由flask框架读取文件。
HTML
头部信息
浏览器标签页的标题
返回字符串的编码方式
body信息
标题
一级标题,随着数字变化标题级数变化
div和span
1 2 3 4 5 6 7 <div > 内容</div > <span > 内容</span >
div中的内容占用一整行,块级标签
span,自己多大占多少,内联标签
超链接
跳转到我的博客,target="_blank"加入是新生成一个标签页
a标签无法直接添加宽度和高度
1 <a href ="https://chuiyugin.github.io/" target ="_blank" > 我的博客</a >
图片
1 <img src ="图片地址" style ="width: 10% ; height: 20%" />
嵌套
1 2 3 <a href ="https://chuiyugin.github.io/" target ="_blank" > <img style ="width: 50%" src ="https://cdn.jsdelivr.net/gh/chuiyugin/imgbed/fast_conv_1.png" /> </a >
列表标签
无序号列表
1 2 3 4 5 <ul > <li > 列表1</li > <li > 列表2</li > <li > 列表3</li > </ul >
带序号列表
1 2 3 4 5 <ol > <li > 列表1</li > <li > 列表2</li > <li > 列表3</li > </ol >
表格
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 <table > <thead > <tr > <th > ID </th > <th > 姓名 </th > <th > 年龄 </th > </tr > </thead > <tbody > <tr > <td > 10</td > <td > fcs</td > <td > 21</td > </tr > <tr > <td > 10</td > <td > xyj</td > <td > 21</td > </tr > <tr > <td > 10</td > <td > shy</td > <td > 21</td > </tr > </tbody > </table >
文本输入
密码输入
选择文件
单选框
1 2 <input type ="radio" name ="n1" > 男<input type ="radio" name ="n1" > 女
复选框
按钮
1 2 <input type ="buton" value ="提交" > --->普通按钮<input type ="submit" value ="提交" > --->提交表单
下拉框
1 2 3 4 5 6 <select > <option > 北京</option > <option > 上海</option > <option > 深圳</option > <option > 广州</option > </select >
多行文本
1 <textarea rows ="3" > </textarea >
请求
GET请求
现象:跳转,向后台传入数据会拼接在URL上。
1 2 3 4 5 6 @app.route("/do/reg" ,methods=['GET' ] ) def do_register (): print (request.args) return "注册成功"
POST请求
现象:提交数据不在URL中,体现在请求体中。
1 2 3 4 5 6 7 8 9 10 @app.route("/post/reg" ,methods=['POST' ] ) def post_register (): print (request.form) user = request.form.get("user" ) psw = request.form.get("psw" ) print (user) print (psw) return "注册成功"
提交数据
form标签包裹要提交的数据标签
提交方式:method="get"或者method=“post”
提交的地址:action=“/xx/xx/xxx”
在form标签里必须要有submit标签
Input系列标签必须要加name,提交时能够解析对应的名字,而且只有Input的内容才会提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 <h1 > 注册界面</h1 > <form method ="post" action ="/post/reg" > <div > 用户名:<input type ="text" name ="user" /> </div > <div > 密码: <input type ="password" name ="psw" /> </div > <div > <input type ="submit" /> </div > </form >
CSS样式
Demo
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 <!DOCTYPE html > <html lang="en"> <head> <meta charset="UTF-8 "> <title>用户注册</title> <link rel="stylesheet" href="/static/commons.css "> <style> .c1 { color :green; } .c2 { height :50px ; } </style> </head> <body > <h1 class="bl">注册界面</h1 > <form method="post" action="/post/reg"> <div class="c2"> 用户名:<input type="text" name="user"/> </div > <div class="c2"> 密码: <input type="password" name="psw"/> </div > <div > <input type="submit" /> </div > </form > </body > </html >
选择器
1 2 3 4 #标识名{ 属性:属性值; 属性:属性值; }
类选择器(用的最多)
1 2 3 4 .类名{ 属性:属性值; 属性:属性值; }
标签选择器
1 2 3 4 5 6 7 input [type='text' ] { border : 1px solid red; }.v1 [xx="123" ] { color :gold; }
先找到包含yy这个类的部分,再将yy内部含有li标签的都变为这个样式。(子子孙孙)
只找子代
样式
高度和宽度
1 2 3 4 .c1 { height :300px width:500px }
宽度支持百分比,高度不支持。
行内标签:默认无效
块级标签:默认有效
块级和行内标签
display: inline-block;
具有行内和块级特性
1 2 3 4 5 6 .c3 { display : inline-block; height :100px ; width :300px ; border : 1px solid red; }
注意:
display: inline;强制行内
display: block;强制块级
字体和颜色
1 2 3 4 5 6 .bl { color :deepskyblue; font-size : 59px ; font-weight : 400 ; font-family : Microsoft Yahei; }
文字对齐方式
1 2 3 4 5 6 7 8 .test { height :100px ; width :300px ; border : 1px solid red; text-align : center; line-height : 100px ; }
浮动
将span内容移动到右边显示
1 2 3 4 <div > <span >测试1 </span > <span style="float :right ">测试2 </span > </div >
浮动之后,块级标签不会占用一整行,但是浮动之后无法破坏了文档流,需要在最后加入
1 <div style="clear : both;"></div >
内边距
边框内部设置内边距,不加左右就是全部
1 2 3 4 5 padding-top :20px ;padding-left :20px ;padding-right :20px ;padding-bottom :20px ;padding :20px ;
外边距
margin-top、margin-left、margin-right、margin-bottom
1 2 <div style="height :200px ;background-color :dodgerblue;"></div > <div style="height :200px ;background-color :red;margin-top :20px ;"></div >
去除外部间距
1 2 3 4 5 <style> body { margin :0 ; } </style>
居中
1 <div style="width :200px ;text-align : center;"></div >
1 2 margin-left :auto;margin-right :auto;
鼠标放上去变色
主要: :hover
1 2 3 .sub-header .menu_list a :hover { color : #ff6700 ; }
position定位
fixed
固定在窗口的某个位置
1 2 3 4 5 6 7 8 .back { position : fixed; width : 60px ; height :60px ; border : 1px solid red; right :0 ; top :500px ; }
relative和absolute
加入absolute的相对relative的位置变化。
BootStrap
导航
组件 · Bootstrap v3 中文文档 | Bootstrap 中文网 (bootcss.com)
栅格
全局 CSS 样式 · Bootstrap v3 中文文档 | Bootstrap 中文网 (bootcss.com)
把整体分为12格
分类
响应式
1 2 3 .col-sm- 750px .col-md- 970px .col-lg- 1170px
非响应式
.col-xs-
1 2 <div class="col-xs-6 " style="background-color : #2aabd2 "> 1</div> <div class=" col-xs-10 " style=" background-color: #5cb85c "> 2 </div>
列偏移
col-xs-offset-2
1 <div class="col-xs-offset-2 col-xs-6 " style="background-color : #2aabd2 "> 1</div>
container
1 2 3 4 <div class="container"> <div class="col-sm-9 ">左边</div > <div class="col-sm-3 ">右边</div > </div >
1 2 3 4 <div class="container-fluid"> <div class="col-sm-9 ">左边</div > <div class="col-sm-3 ">右边</div > </div >
图标
1.bootsrap
2.font awesome
1 <script src ="https://kit.fontawesome.com/5 efd8aed42.js" crossorigin=" anonymous"></script>
JavaScript
是一门编程语言,浏览器是JavaScript语言的解释器。
1 2 <script src ="static/js/jquery-3.6 .1 .min .js "></script> <script src ="static/plugins/bootstrap-3.4 .1 /js/bootstrap.min .js "></script>
DOM和BOM
相当于语言的内置模块
DOM
DOM,就是一个模块,模块可以对HTML页面中的标签进行操作
1 2 3 4 5 var tag = document .createElementById("div" ); tag.innerText = "123" ;
1 2 3 4 5 var tag = document .getElementById("xx" ); tag.innerText = "123" ;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 <ul id ="city" > </ul > <script type ="text/javascript" > var cityList = ["北京" , "上海" , "深圳" , "广州" ]; for (var idx in cityList) { var text = cityList[idx]; var tag = document .createElement("li" ); tag.innerText = text; var parent = document .getElementById("city" ); parent.append(tag); } </script >
jQuery
相当于第三方模块
变量
1 2 var name = "小明" ;console .log(name);
字符串类型
1 2 var name = "小明" ;var name = String ("小明" );
1 2 3 4 5 6 7 var name = "中国联通" ;var v1 = name.length;var v2 = name[0 ];var v3 = name.trim();var v4 = name.substring(0 ,2 );
数组
定义
1 2 var v1 = [11 ,22 ,33 ,44 ];var v2 = Array ([11 ,22 ,33 ,44 ]);
操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 var v1 = [11 ,22 ,33 ,44 ];var v2 = v1[0 ]; v1[0 ] = "小明" ; v1.push("联通" ); v1.unshift("移动" ); v1.splice(1 ,0 ,"元素" ); v1.pop() v1.shift() v1.splice(索引位置,1 ); v1.splice(2 ,1 );
循环
1 2 3 4 5 6 var v1 = [11 ,22 ,33 ,44 ];for (var idx in v1){ }
1 2 3 4 5 6 var v1 = [11 ,22 ,33 ,44 ];for (var i=0 ;i<v1.length;i++){ }
动态标签
1 2 3 4 5 6 7 8 9 10 11 12 var cityList=["北京" ,"上海" ,"深圳" ,"广州" ]; for (var idx in cityList){ var text = cityList[idx]; var tag = document .createElement("li" ); tag.innerText = text; var parent = document .getElementById("city" ); parent.append(tag); }
对象(字典)
1 2 3 4 info = { name :"小明" age :18 }
对对象进行操作
1 2 3 info.age info.name="小红" ; delete info["name" ];
对对象进行循环
1 2 3 for (var key in info){ }
动态表格
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 var dataList = [ {id : 1 , name : "小明" , age : 19 }, {id : 2 , name : "小白" , age : 19 }, {id : 3 , name : "小红" , age : 19 }, {id : 4 , name : "小军" , age : 19 }, {id : 5 , name : "小李" , age : 19 } ]; for (idx in dataList) { var info = dataList[idx]; var tr = document .createElement("tr" ); for (var key in info) { var my_text = info[key]; var td = document .createElement("td" ) td.innerText = my_text; tr.appendChild(td); } var body_tag = document .getElementById("body" ); body_tag.append(tr); }
条件语句
1 2 3 4 5 6 7 if ( 条件 ) { }else if { }else { }
函数
1 2 3 4 5 6 function func ( ) { ... } func();
事件绑定
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 <input type ="text" placeholder ="请输入内容" id ="my_txt" > <input type ="button" value ="点击添加" onclick ="addCityInfo()" > <ul id ="my_city" > </ul > <script type ="text/javascript" > function addCityInfo ( ) { var txtTag = document .getElementById("my_txt" ); var new_string = txtTag.value; if (new_string.length > 0 ) { var newTag = document .createElement("li" ); newTag.innerText = new_string; var parentTag = document .getElementById("my_city" ); parentTag.appendChild(newTag); txtTag.value = "" ; }else { alert("输入不能为空!" ); } } </script >
JQuery
初识JQuery
1 2 3 4 5 6 7 8 9 10 11 <h1 id ="JQ_test" > JQuery测试 </h1 > <script src ="static/js/jquery-3.6.1.min.js" > </script > <script type ="text/javascript" > $("#JQ_test" ).text("JQ修改" ); </script >
直接寻找标签
1 <h1 id ="JQ_test" > JQuery测试 </h1 >
1 <h1 class ="c1" > 中国联通</h1 >
1 2 3 4 5 <div class ="c1" > <span class ="c2" > <a href ="#" > </a > </span > </div >
选择多个标签同时操作
1 2 3 4 5 6 7 8 <div class ="c1" > <span class ="c2" > </span > <a href ="#" > </a > </div > <ul id ="u1" > <li > </li > </ul > <p class ="p1" > </p >
1 2 <input type ="text" name ="n1" > <input type ="text" name ="n2" >
间接寻找标签
1 2 3 4 5 6 <div > <div > 北京</div > <div id ="c1" > 上海</div > <div > 广州</div > <div > 深圳</div > </div >
1 2 3 4 5 $("#c1" ).prev() $("#c1" ) $("#c1" ).next() $("#c1" ).next().next() $("#c1" ).siblings()
1 2 3 4 5 6 7 8 9 10 <div > <div > <div id ="c1" > 上海</div > </div > </div > <div id ="c2" > <div > 老大</div > <div class ="d2" > 老二</div > </div >
1 2 3 4 5 6 $("#c1" ).parent() $("#c1" ).parent().parent() $("#c2" ).children() $("#c2" ).children(".d2" ) $("#c2" ).find(".d2" ) $("#c2" ).find("div" )
案例:菜单切换
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 <!DOCTYPE html > <html lang ="en" > <head > <meta charset ="UTF-8" > <title > 菜单</title > <style > .menu { width : 200px ; height : 800px ; border : 1px solid #2aabd2 ; } .menu .header { cursor : pointer; padding : 10px 5px ; border-bottom : 1px dotted #ddd ; background : linear-gradient (#37ff00 , #16a5d3 ); } .item a { display : block; text-decoration : none; padding : 5px 5px ; border-bottom : 1px dotted #ddd ; } .hide { display : none; } </style > </head > <body > <div class ="menu" > <div class ="item" > <div class ="header" onclick ="clickme(this)" > 北京</div > <div class ="content hide" > <a href ="" > 海淀区</a > <a href ="" > 朝阳区</a > <a href ="" > 大兴区</a > <a href ="" > 昌平区</a > </div > </div > <div class ="item" > <div class ="header" onclick ="clickme(this)" > 上海</div > <div class ="content hide" > <a href ="" > 宝山区</a > <a href ="" > 普陀区</a > <a href ="" > 浦东新区</a > <a href ="" > 青浦区</a > </div > </div > <div class ="item" > <div class ="header" onclick ="clickme(this)" > 北京2</div > <div class ="content hide" > <a href ="" > 海淀区</a > <a href ="" > 朝阳区</a > <a href ="" > 大兴区</a > <a href ="" > 昌平区</a > </div > </div > <div class ="item" > <div class ="header" onclick ="clickme(this)" > 上海2</div > <div class ="content hide" > <a href ="" > 宝山区</a > <a href ="" > 普陀区</a > <a href ="" > 浦东新区</a > <a href ="" > 青浦区</a > </div > </div > </div > <script src ="static/js/jquery-3.6.1.min.js" > </script > <script type ="text/javascript" > function clickme (self ) { $(self).next().removeClass("hide" ); $(self).parent().siblings().find(".content" ).addClass("hide" ); } </script > </body > </html >
操作样式
addClass
removeClass
hasClass
值的操作
1 2 $("#c1" ).text() $("#c1" ).text("测试" )
1 <input type ="text" id ="c2" >
1 2 $("c2" ).val() $("c2" ).val("txt" )
案例:动态创建数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 <!DOCTYPE html > <html lang ="en" > <head > <meta charset ="UTF-8" > <title > 动态创建数据</title > </head > <body > <input type ="text" id ="txtUser" placeholder ="用户名" > <input type ="text" id ="txtEmail" placeholder ="邮箱" > <input type ="button" value ="提交" onclick ="getinfo()" > <ul id ="view" > </ul > <script src ="static/js/jquery-3.6.1.min.js" > </script > <script > function getinfo ( ) { let username = $("#txtUser" ).val(); let email = $("#txtEmail" ).val(); const datastr = username + '-' + email; let lusr = $("<li>" ).text(datastr); $("#view" ).append(lusr); } </script > </body > </html >
事件
绑定事件直接用 $("")
获取到标签直接定义事件即可 。
1 2 3 4 $(".item" ).children().click(function ( ) { $(this ).text("hello python" ) $(this ).remove() })
案例:设置和删除标签
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 <!DOCTYPE html > <html lang ="en" > <head > <meta charset ="UTF-8" > <title > 设置和删除标签</title > <style > .item a { display : block; text-decoration : none; } </style > </head > <body > <div class ="item" > <p href ="" > 1</p > <p href ="" > 2</p > <p href ="" > 3</p > </div > <script src ="static/js/jquery-3.6.1.min.js" > </script > <script > let a = $(".item" ).children(); $(a).click(function ( ) { $(this ).text("hello python" ); $(this ).remove(); }) </script > </body > </html >
当页面框架加载完成之后执行代码(封装在$function之内):
1 2 3 4 5 6 7 <script > $(function ( ) { $(".item" ).children().click(function ( ) { $(this ).text("hello python" ); }) }) </script >
案例:表格操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 <!DOCTYPE html > <html lang ="en" > <head > <meta charset ="UTF-8" > <title > Title</title > </head > <body > <table border ="1" > <thead > <tr > <th > ID</th > <th > 姓名</th > <th > 操作</th > </tr > </thead > <tbody > <tr > <td > 1</td > <td > Alleyf</td > <td > <input type ="button" value ="删除" class ="delete" > </td > </tr > <tr > <td > 2</td > <td > CHUIYUGIN</td > <td > <input type ="button" value ="删除" class ="delete" > </td > </tr > <tr > <td > 3</td > <td > 小明</td > <td > <input type ="button" value ="删除" class ="delete" > </td > </tr > </tbody > </table > <script src ="static/js/jquery-3.6.1.min.js" > </script > <script > $(function ( ) { $(".delete" ).click(function ( ) { $(this ).parent().parent().remove(); }) }) </script > </body > </html >
前端整合
HTNL
CSS
JavaScript
Bootstrap(动态效果依赖jQuery)
案例:添加数据页面
人员信息录入功能,需要提供用户信息:
用户名、年龄、薪资、部门、入职时间(*)
时间的选择:不能输入;选择:(插件)datetimepicker
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 <!DOCTYPE html > <html lang ="en" > <head > <meta charset ="UTF-8" > <title > 添加数据页面</title > <link rel ="stylesheet" href ="static/plugins/bootstrap-3.4.1/css/bootstrap.min.css" > <link rel ="stylesheet" href ="static/plugins/bootstrap-datetimepicker-master/css/bootstrap-datetimepicker.min.css" > </head > <body > <div class ="container" style ="margin-top: 20px" > <form class ="form-horizontal" > <div class ="row clearfix" > <div class ="col-xs-6" > <div class ="form-group" > <label class ="col-sm-2 control-label" > 姓名</label > <div class ="col-sm-10" > <input type ="email" class ="form-control" placeholder ="姓名" > </div > </div > </div > <div class ="col-xs-6" > <div class ="form-group" > <label class ="col-sm-2 control-label" > 年龄</label > <div class ="col-sm-10" > <input type ="email" class ="form-control" placeholder ="年龄" > </div > </div > </div > </div > <div class ="row clearfix" > <div class ="col-xs-6" > <div class ="form-group" > <label class ="col-sm-2 control-label" > 薪资</label > <div class ="col-sm-10" > <input type ="email" class ="form-control" placeholder ="薪资" > </div > </div > </div > <div class ="col-xs-6" > <div class ="form-group" > <label class ="col-sm-2 control-label" > 部门</label > <div class ="col-sm-10" > <select class ="form-control" name ="brabch" id ="inputbranch" > <option value ="" > IT部门</option > <option value ="" > 销售部门</option > <option value ="" > 人事资源管理部门</option > <option value ="" > 售后部门</option > <option value ="" > 运营部门</option > </select > </div > </div > </div > </div > <div class ="row clearfix" > <div class ="col-xs-6" > <div class ="form-group" > <label class ="col-sm-2 control-label" > 入职日期</label > <div class ="col-sm-10" > <input id ="dt" type ="email" class ="form-control" placeholder ="入职日期" > </div > </div > </div > </div > <div class ="form-group" > <div class ="col-sm-offset-6 col-sm-10" > <button type ="submit" class ="btn btn-primary" > 提 交</button > </div > </div > </form > </div > <script src ="https://kit.fontawesome.com/5efd8aed42.js" crossorigin ="anonymous" > </script > <script src ="static/js/jquery-3.6.1.min.js" > </script > <script src ="static/plugins/bootstrap-3.4.1/js/bootstrap.js" > </script > <script src ="static/plugins/bootstrap-datetimepicker-master/js/bootstrap-datetimepicker.js" > </script > <script src ="static/plugins/bootstrap-datetimepicker-master/js/locales/bootstrap-datetimepicker.zh-CN.js" > </script > <script type ="text/javascript" > $(function ( ) { $('#dt' ).datetimepicker({ fomat : 'yyyy-mm-dd' , startDate : '0' , language : 'zh-CN' , autoclose : true }); }); </script > </body > </html >
MySQL
进入MySQL:cmd进入终端
查看
退出
基本数据类型
类型
用途
tinyint
短整形(),相当于java的short,有符号(默认),取值范围:-128127;无符号(用关键词unsigned指定),取值范围:0 255
int
整形,相当于java的int
bigint
长整形,相当于java的long
float
单精度浮点型
double
双精度浮点型
decimal
准确的小数值,eg:wage decimal(m,n) –总共m位数(负号不算),其中小数点后有n位,mmax =65,nmax =30.
datatime
日期类型,YYYY-MM-DD HH:MM:SS(2022-12-09 21:03:00),dt转为字符串类型显示**(dt.strftime(“%Y-%m-%d %H:%M:%S”))**
data
日期类型(无时分秒)YYYY-MM-DD
timestamp
日期类型(可存储时间戳)
char
定长字符,固定字符长度,最大255个字符,速度快,常存储:手机号,邮箱,加密后的密码等
varchar
不定长字符,有多少存多少,最大65535个字节,节省空间,长度是动态变化的。
text
大文字,用于存储很长的字符内容,可存储65535个字符,例如:文章,新闻等。
mediumtext
中等文本,最多存储16777215(224 -1)个字符
longtext
长文本,最多存储4294967295(4GB)(232 -1)个字符
blob
字节数据类型,存储图片、音频等文件
数据库管理(文件夹)
1 2 create database 数据库名;create database 数据库名 DEFAULT CHARSET utf8 COLLATE utf8_general_ci;
数据表管理
1 2 3 4 5 6 create table 表名( 字段名 类型, 字段名 类型, ··· 字段名 类型 )default charset= utf8;
1 2 3 4 5 6 7 create table 表名( 字段名 类型 not null auto_increment primary key, 字段名 类型 not null , 字段名 类型 default 3 , ··· 字段名 类型 null )default charset= utf8;
主键一般用于表示当前行的编号 (类似于身份证)。
1 2 3 4 5 create table medocsys( id int not null auto_increment primary key, name varchar (20 ) not null , pwd varchar (15 ) not null ) default charset= utf8;
1 2 3 4 单条插入insert into 表名(字段名1 ,字段名2 ,···,字段名) values (数据1 ,数据2 ,···,数据); 批量插入insert into 表名(字段名1 ,字段名2 ,···,字段名) values (数据1 ,数据2 ,···,数据),(数据1 ,数据2 ,···,数据),···(数据1 ,数据2 ,···,数据);
数据行操作
新增数据
1 2 3 4 单条插入insert into 表名(字段名1 ,字段名2 ,···,字段名) values (数据1 ,数据2 ,···,数据); 批量插入insert into 表名(字段名1 ,字段名2 ,···,字段名) values (数据1 ,数据2 ,···,数据),(数据1 ,数据2 ,···,数据),···(数据1 ,数据2 ,···,数据);
删除数据
1 2 delete from 表名;delete from 表名 where 条件;
delete from tb1 where id>=10 or name=”yugin”;
修改数据
1 2 3 4 update 表名 set 字段名= 值; update 表名 set 字段名1 = 值,字段名2 = 值; update 表名 set 字段名= 值 where 条件; eg:update tb1 set name= "yugin", pwd= pwd+ "10";
查询数据
1 2 3 4 5 6 查询表所有数据select * from 表名; 查询对应字段的数据select 字段名1 ,字段名2 from 表名; 条件查询数据select * from 表名 where id > 3 ;
小结
一般开发:
提前用工具创建好
1 create database unicom DEFAULT CHARSET utf8 COLLATE utf8_general_ci;
1 2 3 4 5 6 create table admin( id int not null auto_increment primary key, username varchar (16 ) not null , password varchar (64 ) not null , mobile char (11 ) not null )default charset= utf8;
Python操作MySQL
在进行增删改的时候需要执行commit
,不然数据库没有数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 import pymysql conn = pymysql.connect(host="127.0.0.1" ,port=3306 ,user="root" ,password="1234" ,charset="utf8" ,db="unicom" ) cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) sql="insert into admin(username,password,mobile) values(%(name)s,%(psw)s,%(mobile)s)" cursor.execute(sql,{"name" :'alleyf2' ,"psw" :'alleyf1234' ,"mobile" :'18127896898' }) conn.commit() cursor.close() conn.close()
在进行查询的时候不需要执行commit
,但是要执行fetchall/fetchone
获取到返回的数据
返回列表的形式,列表里面包含字典。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 import pymysql conn = pymysql.connect(host="127.0.0.1" ,port=3306 ,user="root" ,password="1234" ,charset="utf8" ,db="unicom" ) cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) sql="select * from admin" cursor.execute(sql) data_list = cursor.fetchall() cursor.execute(sql) my_first = cursor.fetchone()for row_dict in data_list: print (row_dict)print (my_first) cursor.close() conn.close()
Django
默认文件介绍
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 │ manage.py 【项目的管理,启动项目,创建app,数据管理】【不能动】【常常用】 │ ├─.idea │ │ .gitignore │ │ misc.xml │ │ modules.xml │ │ mysite.iml │ │ workspace.xml │ │ │ └─inspectionProfiles │ profiles_settings.xml │ ├─mysite │ │ settings.py 【项目配置文件】【常修改】 │ │ urls.py 【URL和函数的对应关系】【常修改】 │ │ asgi.py 【接收网络请求】【不能动】 │ │ wsgi.py 【接收网络请求】【不能动】 │ │ __init__.py │ │ │ └─__pycache__ │ settings.cpython-310 .pyc │ __init__.cpython-310 .pyc │ └─__pycache__ manage.cpython-310 .pyc
APP
创建APP
1 python manage.py startapp [名字]
1 2 3 4 5 6 7 -项目 -app,用户管理【表结构、函数、HTML 模板、CSS等独立】 -app,订单管理【表结构、函数、HTML 模板、CSS等独立】 -app,后台管理【表结构、函数、HTML 模板、CSS等独立】 -app,网站管理【表结构、函数、HTML 模板、CSS等独立】 -app,API 【表结构、函数、HTML 模板、CSS等独立】 ···
basic 1 2 3 4 5 6 7 8 9 10 ├─app1 │ │ admin.py 【固定,不用动】django默认提供了admin后台管理 │ │ apps.py 【固定,不用动】app启动类 │ │ models.py 【重要,模型层】对数据库操作 │ │ tests.py 【固定,不用动】单元测试 │ │ views.py 【重要,视图层】前后端交互处理请求返回结果的函数 │ │ __init__.py │ │ │ └─migrations 【固定,不用动】数据库变更记录 │ __init__.py
快速上手
1 2 3 4 5 6 7 8 INSTALLED_APPS = [ "django.contrib.admin" , "django.contrib.auth" , "django.contrib.contenttypes" , "django.contrib.sessions" , "django.contrib.messages" , "django.contrib.staticfiles" , "app01.apps.App01Config"
1 2 3 4 5 6 7 8 from django.contrib import adminfrom django.urls import pathfrom app01 import views urlpatterns = [ path("index/" , views.index), ]
1 2 3 4 5 6 from django.shortcuts import render, HttpResponsedef index (request ): return HttpResponse("欢迎访问YUGIN Blog" )
1 2 3 4 1. 命令行启动 python manage.py runserver2. pycharm启动 直接点击pycharm里的启动按钮
编写页面
引入HTML
1 2 3 def user_list (request ): return render(request, "user_list.html" )
静态文件
一般开发过程中:
都会当做静态文件处理!
一般在app目录下放置static文件夹
注意Django一般引入静态文件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 {% load static %}<!DOCTYPE html > <html lang ="en" > <head > <meta charset ="UTF-8" > <title > 用户列表</title > <link rel ="stylesheet" href ="{% static 'plugins/bootstrap-3.4.1/css/bootstrap.css' %}" > </head > <body > <h1 > 用户列表</h1 > <script src ="{% static 'js/jquery-3.6.1.min.js' %}" > </script > <script src ="{% static 'plugins/bootstrap-3.4.1/js/bootstrap.min.js' %}" > </script > </body > </html >
模板语法
views.py
1 2 3 4 5 6 7 8 9 10 11 12 def tpl (request ): name = "小明" roles = ["管理员" , "CEO" , "保安" ] user_info = {"name" : "郭志" , "salary" : "101000" , "role" : "CTO" } data_list = [ {"name" : "郭志" , "salary" : "101000" , "role" : "CTO" }, {"name" : "赵健" , "salary" : "1010" , "role" : "保安" }, {"name" : "芦荟" , "salary" : "201000" , "role" : "CEO" } ] return render(request, "tpl.html" , {"n1" : name, "n2" : roles, "n3" : user_info,"n4" :data_list})
HTML
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 <!DOCTYPE html > <html lang ="en" > <head > <meta charset ="UTF-8" > <title > 模板语法的学习</title > </head > <body > <h1 > 模板语法的学习</h1 > {#字符串#}<div > {{ n1 }}</div > {#列表#}<div > {{ n2.0 }}</div > <div > {{ n2.1 }}</div > <div > {{ n2.2 }}</div > {#循环列表#}<div > {% for item in n2 %} <span > {{ item }}</span > {% endfor %}</div > {#字典#}<span > {{ n3.name }}</span > <span > {{ n3.salary }}</span > <span > {{ n3.role }}</span > {#循环字典#}<ul > {% for key,valuse in n3.items %} <li > {{ key }} = {{ valuse }}</li > {% endfor %}</ul > {#列表套字典#}<ul > <li > {{ n4.1 }}</li > <li > {{ n4.1.name }}</li > </ul > {#列表套字典加循环#}<ul > {% for item in n4 %} <li > {{ item.name }} = {{item.salary }}</li > {% endfor %}</ul > {#条件语句#} {% if n1 == "小明"%} <h1 > 是小明</h1 > {% else %} <h1 > 不是小明</h1 > {% endif %}</body > </html >
案例:热搜展示
views.py
1 2 3 4 5 6 7 8 def news (request ): url = "http://api.54dh.cn/API/search/rs/?type=weibo" dic = {'user-agent' : 'Mozilla/5.0' } r = requests.post(url, headers=dic) r.raise_for_status() r.encoding = r.apparent_encoding info = {'info' : r.json()} return render(request, "news.html" , info)
HTML
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 {% load static %}<!DOCTYPE html > <html lang ="en" > <head > <meta charset ="UTF-8" > <title > 热搜展示</title > <link rel ="stylesheet" href ="{% static 'plugins/bootstrap-3.4.1/css/bootstrap.css' %}" > <style > * { padding : 0 ; margin : 0 ; font-family : 微软雅黑, serif; letter-spacing : .05em ; } .container { margin : 5px auto; background-image : linear-gradient (to right, #a997a4 , #b3e8ee ); } </style > </head > <body > <div class ="row container" > <h1 class ="col-xs-12 text-center" > 热搜展示---{{ info.time }}</h1 > <div class =" text-center" > {% for item in info.data %} <a href ="{{ item.link }}" > {{ item.title }}--{{ item.heat }}</a > <br > {% endfor %} </div > </div > <script src ="{% static 'js/jquery-3.6.1.min.js' %}" > </script > <script src ="{% static 'plugins/bootstrap-3.4.1/js/bootstrap.min.js' %}" > </script > </body > </html >
请求和响应
通过此方式可以获取到get请求中的参数和post请求中的数据
1 2 3 4 5 6 7 8 9 def something (request ): if request.method == "GET" : parameters = request.GET data = request.POST print (parameters) print (data) return HttpResponse(parameters['name' ])
重定向:返回重定向的网址给浏览器,浏览器去请求该网址
1 return redirect("https://www.baidu.com" )
案例:用户登录
views.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 from django.shortcuts import render, HttpResponse,redirectimport requestsdef login (request ): if request.method == "GET" : return render(request, "login.html" ) else : username=request.POST.get("user" ) pwd = request.POST.get("pwd" ) if username == 'root' and pwd == '1234' : return redirect("http://chuiyugin.github.io" ) else : return render(request, "login.html" ,{"error_msg" :"用户名或密码错误" })
HTML
注意: 在html表单(form)中加上{% csrf_token %}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 {% load static %}<!DOCTYPE html > <html lang ="en" > <head > <meta charset ="UTF-8" > <title > 用户登录</title > <link rel ="stylesheet" href ="{% static 'plugins/bootstrap-3.4.1/css/bootstrap.css' %}" > </head > <body > <form method ="post" action ="/login/" > {#提交表单一定要添加#} {% csrf_token %} <input type ="text" name ="user" placeholder ="用户名" > <input type ="password" name ="pwd" placeholder ="密码" > <input type ="submit" value ="提交" > <div class ="row container" > <h2 class ="col-xs-12 " style ="color:darkred;" > {{ error_msg }}</h2 > </div > </form > <script src ="{% static 'js/jquery-3.6.1.min.js' %}" > </script > <script src ="{% static 'plugins/bootstrap-3.4.1/js/bootstrap.min.js' %}" > </script > </body > </html >
数据库操作
Django使用ORM框架实现对数据库的操作,安装mysqlclient
第三方库辅助操作
ORM
ORM可以帮助我们完成两件事:
创建、修改、删除数据库中的表(不用写SQL语句)【无法创建数据库】
操作表中的数据
配置setting.py文件
1 2 3 4 5 6 7 8 9 10 DATABASES = { 'default' : { 'ENGINE' : 'django.db.backends.mysql' , 'NAME' : 'day15' , 'USER' : 'root' , 'PASSWORD' : '1234' , 'HOST' : '127.0.0.1' , 'PORT' : 3306 , } }
Django操作表
创建表
1 2 3 4 5 6 7 8 9 from django.db import modelsclass Userinfo (models.Model ): name = models.CharField(max_length=32 ) password = models.CharField(max_length=64 ) mobile = models.CharField(max_length=11 ) email = models.CharField(max_length=32 ) age = models.IntegerField()
注意:1.终端路径在项目名目录下。2.app需要已经注册。3.表名是app的名称加上类名
1 2 python manage.py makemigrations python manage.py migrate
删除表
直接将models.py
里面的类注释掉即可
1 2 3 4 5 6 7 8 class Userinfo (models.Model ):
修改表
1 2 3 4 5 6 7 8 9 class Userinfo (models.Model ): name = models.CharField(max_length=32 ) password = models.CharField(max_length=64 ) mobile = models.CharField(max_length=11 ) email = models.CharField(max_length=32 ) age = models.IntegerField() docpath = models.CharField(max_length=64 , default="" )
1 2 docpath = models.CharField(max_length=128 , default="" )
在表中新建字段(列)时,由于已存在的字段可能已有数据,所以新增列必须要指定新增列对应的数据:
手动输入一个值(全部行都为输入的值)
设置默认值(default后面的值)
1 2 docpath = models.CharField(default="" ) docpath = models.CharField(default=2 )
允许为空
1 imgpath = models.CharField(null=True , blank=True )
操作表中的数据
添加数据( models.py )
1 2 3 Userinfo.objects.create(name="yugin" , password="123456" , mobile="18127896898" , email="1726123207@qq.com" )
在views.py中引入models.py中的类即可进行添加数据:
1 2 class Department (models.Model ): title = models.CharField(max_length=16 )
1 2 3 4 5 6 7 8 9 from app01.models import Department,Userinfodef orm (request ): Department.objects.create(title="销售部门" ) Department.objects.create(title="IT部门" ) Department.objects.create(title="运营部门" ) return HttpResponse("成功" )
更新数据
1 2 3 4 Userinfo.objects.filter (id =2 ).update(password='a123456' ) Userinfo.objects.all ().update(mobile='13125018525' )
删除数据
1 2 3 4 Userinfo.objects.filter (id =2 ).delete() Userinfo.objects.all ().delete()
查询数据
1 2 3 4 5 6 7 8 userinfo = Userinfo.objects.filter (id =1 ) userobj = Userinfo.objects.filter (id =1 ).first() userinfo = Userinfo.objects.all ()
1 2 3 4 5 6 7 8 def user_list (request ): userlist = [] userinfo = Userinfo.objects.all () for info in userinfo: datadic = {'id' : info.id , 'name' : info.name, 'password' : info.password, 'mobile' : info.mobile, 'email' : info.email} userlist.append(datadic) print (userlist) return render(request, "user_list.html" , {'userlist' : userlist})
案例:用户管理
要求:
展示用户列表
url路由
view函数
获取用户信息
HTML渲染
添加用户
删除用户
a标签传递用户id参数get请求
筛选删除指定用户
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 {% load static %}<!DOCTYPE html > <html lang ="en" > <head > <meta charset ="UTF-8" > <title > 用户管理系统</title > <link rel ="stylesheet" href ="{% static 'plugins/bootstrap-3.4.1/css/bootstrap.css' %}" > </head > <body > <h1 > INFO列表</h1 > <a href ="/info/add/" > 点此添加数据</a > <table border ="1" > <thead > <tr > <th > ID</th > <th > 姓名</th > <th > 密码</th > <th > 年龄</th > <th > 操作</th > </tr > </thead > <tbody > {% for obj in data_list %} <tr > <td > {{ obj.id }}</td > <td > {{ obj.name }}</td > <td > {{ obj.password }}</td > <td > {{ obj.age }}</td > <td > <a href ="/info/delete/?nid={{ obj.id }}" > 删除</a > </td > </tr > {% endfor %} </tbody > </table > <script src ="{% static 'js/jquery-3.6.1.min.js' %}" > </script > <script src ="{% static 'plugins/bootstrap-3.4.1/js/bootstrap.min.js' %}" > </script > </body > </html >
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 {% load static %}<!DOCTYPE html > <html lang ="en" > <head > <meta charset ="UTF-8" > <title > 用户管理系统</title > <link rel ="stylesheet" href ="{% static 'plugins/bootstrap-3.4.1/css/bootstrap.css' %}" > </head > <body > <h1 > 添加用户</h1 > <form method ="post" action ="/info/add/" > {% csrf_token %} <input type ="text" name ="user" placeholder ="用户名" > <input type ="text" name ="pwd" placeholder ="密码" > <input type ="text" name ="age" placeholder ="年龄" > <input type ="submit" value ="提 交" > </form > <script src ="{% static 'js/jquery-3.6.1.min.js' %}" > </script > <script src ="{% static 'plugins/bootstrap-3.4.1/js/bootstrap.min.js' %}" > </script > </body > </html >
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 from django.shortcuts import render, HttpResponse,redirectimport requestsfrom app01.models import Department,Userinfodef orm (request ): Department.objects.create(title="销售部门" ) Department.objects.create(title="IT部门" ) Department.objects.create(title="运营部门" ) return HttpResponse("成功" )from app01.models import Department,Userinfodef info_list (request ): data_list = Userinfo.objects.all () return render(request, "info_list.html" ,{"data_list" :data_list})def info_add (request ): if request.method == "GET" : return render(request, "info_add.html" ) user = request.POST.get("user" ) pwd = request.POST.get("pwd" ) age = request.POST.get("age" ) Userinfo.objects.create(name=user,password=pwd,age=age) return redirect("/info/list/" )def info_delete (request ): nid = request.GET.get("nid" ) Userinfo.objects.filter (id =nid).delete() return redirect("/info/list/" )
Django开发
设置表结构
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 from django.db import modelsclass Department (models.Model ): """部门表""" title = models.CharField(verbose_name="标题" , max_length=32 )class UserInfo (models.Model ): """员工表""" name = models.CharField(verbose_name="姓名" , max_length=16 ) password = models.CharField(verbose_name="密码" , max_length=16 ) age = models.IntegerField(verbose_name="年龄" ) account = models.DecimalField(verbose_name="账户余额" , max_digits=10 , decimal_places=2 , default=0 ) create_time = models.DateTimeField(verbose_name="入职时间" ) gender_choices = ( (1 , '男' ), (2 , '女' ), ) gender = models.SmallIntegerField(verbose_name='性别' , choices=gender_choices) depart = models.ForeignKey(to='Department' , to_field='id' , on_delete=models.CASCADE)
部门管理
部门列表
重要知识点 : url中传递动态参数
1 2 path("depart/<int:nid>/edit/" , views.depart_edit),
1 2 3 4 5 6 7 8 def depart_list (request ): """部门列表""" queryset = models.Department.objects.all () return render(request, "depart_list.html" , {"queryset" : queryset})
新建部门
1 2 3 4 5 6 7 8 9 10 def depart_add (request ): """添加部门""" if request.method == "GET" : return render(request, "depart_add.html" ) title = request.POST.get("title" ) models.Department.objects.create(title=title) return redirect("/depart/list/" )
删除部门
1 2 3 4 5 def depart_delete (request ): """删除部门""" nid = request.GET.get("nid" ) models.Department.objects.filter (id =nid).delete() return redirect("/depart/list/" )
修改部门
重要知识点 : url中传递动态参数
1 2 path("depart/<int:nid>/edit/" , views.depart_edit),
1 2 3 4 5 6 7 8 9 10 def depart_edit (request,nid ): """修改部门""" if request.method == "GET" : row_object = models.Department.objects.filter (id =nid).first() return render(request, "depart_edit.html" ,{"row_object" :row_object}) if request.method == "POST" : title = request.POST.get("title" ) models.Department.objects.filter (id =nid).update(title=title) return redirect("/depart/list/" )
HTML模板继承
模板继承可以使父模板的内容复用,子模版直接继承父模板的全部内容并可以覆盖父模板中相应的块。
语法—父模板中:
1.定义父模板中的块block标签
2.标识出哪些在子模版中是允许被修改的
3.block标签:在父模板中定义,可以在子模版中覆盖
1 2 3 {% block block_name %} 父模板可以被覆盖的内容 {% endblock blocl_name%} (**切记一定要写endblock**)
语法—子模版中:
1.继承模板extends标签(写在模板文件的第一行 )
1 {% entends 'layout.html' %}
2.子模版 重写父模板中的内容块
1 2 3 {% block block_name %} 子模版用来覆盖父模板中 block_name 块的内容 {% endblock blocl_name%} (**切记一定要写endblock**)
实例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 {% extends "layout.html" %} {% block content %} <div class ="container" > <div > <a href ="/depart/add/" class ="btn btn-primary" > 新建部门</a > </div > <div class ="panel panel-default" style ="margin-top: 20px" > <div class ="panel-heading" > <span class ="glyphicon glyphicon-pushpin" aria-hidden ="true" > </span > 部门列表 </div > <table class ="table" > <thead > <tr > <th > ID</th > <th > 部门名称</th > <th > 操作</th > </tr > </thead > <tbody > {% for obj in queryset %} <tr > <td > {{ obj.id }}</td > <td > {{ obj.title }}</td > <td > <a class ="btn btn-success btn-xs" href ="/depart/{{ obj.id }}/edit/" > 编辑</a > <a class ="btn btn-danger btn-xs" href ="/depart/delete/?nid={{ obj.id }}" > 删除</a > </td > </tr > {% endfor %} </tbody > </table > </div > </div > {% endblock %}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 {% extends "layout.html" %} {% block content %} <div class ="container" > <div > <a href ="/depart/add/" class ="btn btn-primary" > 新建部门</a > </div > <div class ="panel panel-default" style ="margin-top: 20px" > <div class ="panel-heading" > <span class ="glyphicon glyphicon-pushpin" aria-hidden ="true" > </span > 部门列表 </div > <table class ="table" > <thead > <tr > <th > ID</th > <th > 部门名称</th > <th > 操作</th > </tr > </thead > <tbody > {% for obj in queryset %} <tr > <td > {{ obj.id }}</td > <td > {{ obj.title }}</td > <td > <a class ="btn btn-success btn-xs" href ="/depart/{{ obj.id }}/edit/" > 编辑</a > <a class ="btn btn-danger btn-xs" href ="/depart/delete/?nid={{ obj.id }}" > 删除</a > </td > </tr > {% endfor %} </tbody > </table > </div > </div > {% endblock %}
主题一:用户管理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 insert into app01_userinfo(name,password,age,account,create_time,gender,depart_id_id) values ("刘冬","1234","23","100.87","2010-1-11","1","1");insert into app01_userinfo(name,password,age,account,create_time,gender,depart_id_id) values ("Alleyf","1234","20","9000.87","2012-1-11","1","2");+ | Field | Type | Null | Key | Default | Extra | + | id | bigint | NO | PRI | NULL | auto_increment | | name | varchar (16 ) | NO | | NULL | | | password | varchar (64 ) | NO | | NULL | | | age | int | NO | | NULL | | | account | decimal (10 ,2 ) | NO | | NULL | | | create_time | datetime(6 ) | NO | | NULL | | | gender | smallint | NO | | NULL | | | depart_id_id | bigint | NO | MUL | NULL | | +
原始方式:不会采用(本质)【麻烦】
没有数据校验
错误,应该有提示
页面上,每个字段都需要我们重新写一遍,数据冗余
关联的数据,需要手动获取并循环展示在页面中
Django组件
Form组件(较简便)
ModelForm组件(最简便)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 class UserInfo (models.Model ): """ 员工表 """ name = models.CharField(verbose_name='姓名' , max_length=16 ) password = models.CharField(verbose_name="密码" , max_length=64 ) age = models.IntegerField(verbose_name="年龄" ) account = models.DecimalField(verbose_name="账户余额" , max_digits=10 , decimal_places=2 , default=0 ) create_time = models.DateTimeField(verbose_name="入职时间" ) depart_id = models.ForeignKey(to="Department" , to_field="id" , on_delete=models.CASCADE,verbose_name="部门" ) gender_choices = ( (1 , '男' ), (2 , '女' ), ) gender = models.SmallIntegerField(verbose_name='性别' , choices=gender_choices)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 def user_list (request ): queryset = models.UserInfo.objects.all () return render(request, "user_list.html" , {"queryset" : queryset})from django import formsclass userInfoForm (forms.ModelForm ): class Meta : model = models.UserInfo fields = ["name" , "password" , "age" , "create_time" , "gender" , "depart_id" ] widgets = { "create_time" : forms.DateTimeInput(attrs={"class" : " form-control input" , "type" : "datetime-local" }), } def __init__ (self, *args, **kwargs ): super ().__init__(*args, **kwargs) for name, field in self.fields.items(): if name == "create_time" : continue field.widget.attrs = {"class" : "input form-control" , "placeholder" : field.label}def user_add (request ): if request.method == "GET" : form = userInfoForm() return render(request, "user_add.html" , {"form" : form}) form = userInfoForm(data=request.POST) if form.is_valid(): form.save() return redirect("/user/list" ) else : return render(request, "user_add.html" ,{"form" : form})
user_list.html(未用ModelForm)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 {% extends "layout.html" %} {% block content %} <div class ="container" > <div > <a href ="/user/add/" class ="btn btn-primary" > 新建用户</a > </div > <div class ="panel panel-default" style ="margin-top: 20px" > <div class ="panel-heading" > <span class ="glyphicon glyphicon-pushpin" aria-hidden ="true" > </span > 用户列表 </div > <table class ="table" > <thead > <tr > <th > ID</th > <th > 姓名</th > <th > 密码</th > <th > 年龄</th > <th > 余额</th > <th > 入职时间</th > <th > 性别</th > <th > 所属部门</th > <th > 操作</th > </tr > </thead > <tbody > {% for obj in queryset %} <tr > <td > {{ obj.id }}</td > <td > {{ obj.name }}</td > <td > {{ obj.password }}</td > <td > {{ obj.age }}</td > <td > {{ obj.account }}</td > <td > {{ obj.create_time|date:"Y-m-d" }}</td > <td > {{ obj.get_gender_display }}</td > <td > {{ obj.depart_id.title }}</td > <td > <a class ="btn btn-success btn-xs" href ="/depart/{{ obj.id }}/edit/" > 编辑</a > <a class ="btn btn-danger btn-xs" href ="/depart/delete/?nid={{ obj.id }}" > 删除</a > </td > </tr > {% endfor %} </tbody > </table > </div > </div > {% endblock %}
user_add.html(使用ModelForm)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 {% extends "layout.html" %} {% block content %} <div class ="container" > <div class ="panel panel-default" > <div class ="panel-heading" > <h3 class ="panel-title" > 新建用户</h3 > </div > <div class ="panel-body" > <form method ="post" novalidate > {% csrf_token %} {% for field in form %} <div class ="form-group" > <label > {{ field.label }}</label > {{ field }} <span style ="color: #2aabd2" > {{ field.errors.0 }}</span > </div > {% endfor %} <button type ="submit" class ="btn btn-primary" > 提 交</button > </form > </div > </div > </div > {% endblock %}
在配置文件settings.py
中可以设置语言种类
1 2 LANGUAGE_CODE = "zh-hans" 中文
主题二:靓号管理
靓号管理