Day17 表單驗證、滾動菜單、WEB框架

1、表單驗證的兩種實現方式javascript

一、DOM綁定css

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>表單驗證(DOM綁定)</title>
    <style>
        .item{
            width: 250px;
            height: 60px;
            position: relative;
        }
        .item input{
            width: 200px;
        }
        .item span{
            position: absolute;
            top: 20px;
            left: 0px;
            font-size: 8px;
            background-color: red;
            color: white;
            display: inline-block;
            width: 200px;
        }
    </style>
</head>
<body>
    <div>
        <form>
            <div class="item">
                <input class="c1" type="text" name="username" label="用戶名" />
                <!--<span>用戶名不能爲空</span>-->
            </div>
            <div class="item">
                <input class="c1" type="password" name="pwd" label="密碼" />
                <!--<span>密碼不能爲空</span>-->
            </div>
            <input type="submit" value="提交" onclick="return CheckValid();" />
             <!--<input type="submit" value="提交" />-->
        </form>
    </div>
    <script src="jquery-1.12.4.js"></script>
    <script>
        function CheckValid() {
            //找到form標籤下的全部須要驗證的標籤
            //$('form .c1')
            //$('form input[type="text"],form input[type="password"]')
            //循環全部須要驗證的標籤,獲取內容
            //移除錯誤提示
            $('form .item span').remove();
            var flag = true;
            $('form .c1').each(function () {
                //每個元素執行一次匿名函數
                //this:當前元素
                //console.log(this,$(this));
                var val = $(this).val();
                if(val.length <=0){
                    var label = $(this).attr('label');
                    var tag = document.createElement('span');
                    tag.innerText = label + "不能爲空";
                    $(this).after(tag);
                    flag = false;
                }
            });
            return flag;
        }
    </script>
</body>
</html>
View Code

二、jQuery綁定html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>表單驗證(jQuery綁定)</title>
    <style>
        .item{
            width: 250px;
            height: 60px;
            position: relative;
        }
        .item input{
            width: 200px;
        }
        .item span{
            position: absolute;
            top: 20px;
            left: 0px;
            font-size: 8px;
            background-color: red;
            color: white;
            display: inline-block;
            width: 200px;
        }
    </style>
</head>
<body>
    <div>
        <form>
            <div class="item">
                <input class="c1" type="text" name="username" label="用戶名" />
                <!--<span>用戶名不能爲空</span>-->
            </div>
            <div class="item">
                <input class="c1" type="password" name="pwd" label="密碼" />
                <!--<span>密碼不能爲空</span>-->
            </div>
            <input type="submit" value="提交" />
        </form>
    </div>
    <script src="jquery-1.12.4.js"></script>
    <script>
        $(function(){
            //當頁面加載完成後自動執行
            BindCheckValid();
        });

        function BindCheckValid() {
            $('form :submit').click(function() {
                //只要點擊submit按鈕,執行此處內容,找到form標籤下的全部須要驗證的標籤
                $('form .item span').remove();
                var flag = true;
                $('form .c1').each(function () {
                    //每個元素執行一次匿名函數
                    //this:當前元素
                    //console.log(this,$(this));
                    var val = $(this).val();
                    if (val.length <= 0) {
                        var label = $(this).attr('label');
                        var tag = document.createElement('span');
                        tag.innerText = label + "不能爲空";
                        $(this).after(tag);
                        flag = false;
                        return false;
                    }
                });
                return flag;
            });
        }
    </script>
</body>
</html>
View Code

2、jQuery補充前端

一、jQuery中each返回值java

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>jQuery中each返回值</title>
    <style>
        .item{
            width: 250px;
            height: 60px;
            position: relative;
        }
        .item input{
            width: 200px;
        }
        .item span{
            position: absolute;
            top: 20px;
            left: 0px;
            font-size: 8px;
            background-color: indianred;
            color: white;
            display: inline-block;
            width: 200px;
        }
    </style>
</head>
<body>

    <div>
        <form>
            <div class="item">
                <input class="c1" type="text" name="username" label="用戶名"/>
                <!--<span>用戶名不能爲空</span>-->
            </div>
            <div class="item">
                <input  class="c1" type="password" name="pwd" label="密碼"/>
                <!--<span>密碼不能爲空</span>-->
            </div>
            <!--<input type="submit" value="提交" onclick="return CheckValid();" />-->
            <input type="submit" value="提交" />
        </form>
    </div>

    <script src="jquery-1.12.4.js"></script>
    <script>

        function BindCheckValid(){

            $.each([11,22,33,44],function(k,v){
                if(v == 22){
                    //return ; // continue
                    return false; //break
                }
                console.log(v);
            })
        }

        BindCheckValid();

    </script>
</body>
</html>
View Code

二、jQuery擴展python

擴展1:jquery

extend1.jsweb

/**
 * Created by WangHuafeng on 2016/10/15.
 */
(function (jq) {
    jq.extend({
        'radar' : function (arg) {
            console.log(arg);
        }
    });
    function f1() {

    }
})(jQuery);
//一、自執行;二、閉包
/*
a = function (jq) {
    //調用時沒有選擇器
    jq.extend({
        'radar' : function (arg) {
            console.log(arg);
        }
    });
    function f1() {

    }
};
a(jQuery);
    */
View Code

extend1.html正則表達式

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>jQuery擴展1</title>
    <style>
        .item{
            width: 250px;
            height: 60px;
            position: relative;
        }
        .item input{
            width: 200px;
        }
        .item span{
            position: absolute;
            top: 20px;
            left: 0px;
            font-size: 8px;
            background-color: indianred;
            color: white;
            display: inline-block;
            width: 200px;
        }
    </style>
</head>
<body>

    <div>
        <form>
            <div class="item">
                <input class="c1" type="text" name="username" label="用戶名"/>
                <!--<span>用戶名不能爲空</span>-->
            </div>
            <div class="item">
                <input  class="c1" type="password" name="pwd" label="密碼"/>
                <!--<span>密碼不能爲空</span>-->
            </div>
            <!--<input type="submit" value="提交" onclick="return CheckValid();" />-->
            <input type="submit" value="提交" />
        </form>
    </div>

    <script src="jquery-1.12.4.js"></script>
    <script src="extend1.js"></script>
    <script>
        $.radar('welcome radar 擴展1');
    </script>
</body>
</html>
View Code

擴展2:數據庫

extend2.js

/**
 * Created by WangHuafeng on 2016/10/15.
 */

(function (jq) {
    //調用的時候能夠有選擇器
    $.fn.extend({
        'radar1' : function (arg) {
            //this:代指前面的選擇器
            console.log(arg);
        }
    });
    function f2() {

    }
})(jQuery);

/*
b = function () {
    //調用的時候能夠有選擇器
    $.fn.extend({
        'radar1' : function (arg) {
            //this:代指前面的選擇器
            console.log(arg);
        }
    });
    function f2() {
        
    }
};
b(jQuery);
*/
View Code

extend2.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>jQuery擴展2</title>
    <style>
        .item{
            width: 250px;
            height: 60px;
            position: relative;
        }
        .item input{
            width: 200px;
        }
        .item span{
            position: absolute;
            top: 20px;
            left: 0px;
            font-size: 8px;
            background-color: indianred;
            color: white;
            display: inline-block;
            width: 200px;
        }
    </style>
</head>
<body>

    <div>
        <form>
            <div class="item">
                <input class="c1" type="text" name="username" label="用戶名"/>
                <!--<span>用戶名不能爲空</span>-->
            </div>
            <div class="item">
                <input  class="c1" type="password" name="pwd" label="密碼"/>
                <!--<span>密碼不能爲空</span>-->
            </div>
            <!--<input type="submit" value="提交" onclick="return CheckValid();" />-->
            <input type="submit" value="提交" />
        </form>
    </div>

    <script src="jquery-1.12.4.js"></script>
    <script src="extend2.js"></script>
    <script>
        $('form').radar1('welcome radar1 擴展2');
    </script>
</body>
</html>
View Code

三、表單驗證jQuery擴展

commons.js

/**
 * Created by WangHuafeng on 2016/10/15.
 */
(function (jq) {
    jq.extend({
        valid:function (form) {
            //#form1    $('#form1')
            jq(form).find(':submit').click(function () {
                jq(form).find('.item span').remove();
                var flag = true;
                jq(form).find(':text,:password').each(function () {
                    var val = $(this).val();
                    if (val.length <= 0) {
                        var label = $(this).attr('label');
                        var tag = document.createElement('span');
                        tag.innerText = label + "不能爲空";
                        $(this).after(tag);
                        flag = false;
                        return false;//至關於break
                    }
                });
                return flag;
            });
        }
    });
})(jQuery);
View Code

j1.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>表單驗證(jQuery擴展)</title>
    <style>
        .item{
            width: 250px;
            height: 60px;
            position: relative;
        }
        .item input{
            width: 200px;
        }
        .item span{
            position: absolute;
            top: 20px;
            left: 0px;
            font-size: 8px;
            background-color: red;
            color: white;
            display: inline-block;
            width: 200px;
        }
    </style>
</head>
<body>
    <div>
        <form id="form1">
            <div class="item">
                <input class="c1" type="text" name="username" label="用戶名" />
            </div>
            <div class="item">
                <input class="c1" type="password" name="pwd" label="密碼" />
            </div>
            <input type="submit" value="提交" />
        </form>
        <form id="form2">
            <div class="item">
                <input class="c1" type="text" name="username" label="用戶名" />
            </div>
            <div class="item">
                <input class="c1" type="password" name="pwd" label="密碼" />
            </div>
            <input type="submit" value="提交" />
        </form>
    </div>
    <script src="jquery-1.12.4.js"></script>
    <script src="commons.js"></script>
    <script>
        $(function () {
            $.valid('#form1');
            //valid:$('#form1')
        });
    </script>
</body>
</html>
View Code

四、表單驗證自定義屬性

commons2.js

/**
 * Created by WangHuafeng on 2016/10/15.
 */
(function (jq) {
    function ErrorMessage(inp,message) {
        var tag = document.createElement('span');
        tag.innerText = message;
        inp.after(tag);
    }
    jq.extend({
        valid:function (form) {
            jq(form).find(':submit').click(function () {
                jq(form).find('.item span').remove();
                var flag = true;
                jq(form).find(':text,:password').each(function () {

                    var require = $(this).attr('require');
                    if(require){
                        var val = $(this).val();
                        if (val.length <= 0) {
                            var label = $(this).attr('label');
                            ErrorMessage($(this),label + "不能爲空");
                            flag = false;
                            return false;//至關於break
                        }
                        var minLen = $(this).attr('min-len');
                        if(minLen){
                            var minLenInt = parseInt(minLen);
                            if(val.length<minLenInt){
                                var label = $(this).attr('label');
                                ErrorMessage($(this),label + "最小長度爲"+ minLen);
                                flag = false;
                                return false;//至關於break
                            }
                            //json.stringfy()
                            //JSON.parse()  字典轉換爲字符串
                        }
                        var phone = $(this).attr('phone');
                        if(phone){
                            //用戶輸入內容是否爲手機號碼格式
                            var phoneReg = /^1[3|5|8]\d{9}$/;
                            if(!phoneReg.test(val)){
                                var label = $(this).attr('label');
                                ErrorMessage($(this),label + "格式錯誤");
                                flag = false;
                                return false;//至關於break
                            }
                        }
                        //自定義標籤格式
                        //驗證
                    }
                });
                return flag;
            });
        }
    });
})(jQuery);
View Code

j2.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>表單驗證(自定義屬性)</title>
    <style>
        .item{
            width: 250px;
            height: 60px;
            position: relative;
        }
        .item input{
            width: 200px;
        }
        .item span{
            position: absolute;
            top: 20px;
            left: 0px;
            font-size: 8px;
            background-color: red;
            color: white;
            display: inline-block;
            width: 200px;
        }
    </style>
</head>
<body>
    <div>
        <form id="form1">
            <div class="item">
                <input class="c1" type="text" name="username" label="用戶名" require="true" min-len="6" />
            </div>
            <div class="item">
                <input class="c1" type="password" name="pwd" label="密碼" />
            </div>
            <div class="item">
                <input class="c1" type="text" name="tel" label="手機號碼" require="true" phone="true" />
            </div>
            <input type="submit" value="提交" />
        </form>
    </div>
    <script src="jquery-1.12.4.js"></script>
    <script src="commons2.js"></script>
    <script>
        $(function () {
            $.valid('#form1');
            //valid:$('#form1')
        });
    </script>
</body>
</html>
View Code

3、滾動菜單

scroll_menu.html

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>

        body{
            margin: 0px;
        }
        img {
            border: 0;
        }
        ul{
            padding: 0;
            margin: 0;
            list-style: none;
        }
        .clearfix:after {
            content: ".";
            display: block;
            height: 0;
            clear: both;
            visibility: hidden;
        }

        .wrap{
            width: 980px;
            margin: 0 auto;
        }
        
        .pg-header{
            background-color: #303a40;
            -webkit-box-shadow: 0 2px 5px rgba(0,0,0,.2);
            -moz-box-shadow: 0 2px 5px rgba(0,0,0,.2);
            box-shadow: 0 2px 5px rgba(0,0,0,.2);
        }
        .pg-header .logo{
            float: left;
            padding:5px 10px 5px 0px;
        }
        .pg-header .logo img{
            vertical-align: middle;
            width: 110px;
            height: 40px;

        }
        .pg-header .nav{
            line-height: 50px;
        }
        .pg-header .nav ul li{
            float: left;
        }
        .pg-header .nav ul li a{
            display: block;
            color: #ccc;
            padding: 0 20px;
            text-decoration: none;
            font-size: 14px;
        }
        .pg-header .nav ul li a:hover{
            color: #fff;
            background-color: #425a66;
        }
        .pg-body{

        }
        .pg-body .catalog{
            position: absolute;
            top:60px;
            width: 200px;
            background-color: #fafafa;
            bottom: 0px;
        }
        .pg-body .catalog.fixed{
            position: fixed;
            top:10px;
        }

        .pg-body .catalog .catalog-item.active{
            color: #fff;
            background-color: #425a66;
        }

        .pg-body .content{
            position: absolute;
            top:60px;
            width: 700px;
            margin-left: 210px;
            background-color: #fafafa;
            overflow: auto;
        }
        .pg-body .content .section{
            height: 500px;
        }
    </style>
</head>
<body>

    <div class="pg-header">
        <div class="wrap clearfix">
            <div class="logo">
                <a href="#">
                    <img src="">
                </a>
            </div>
            <div class="nav">
                <ul>
                    <li>
                        <a  href="#">首頁</a>
                    </li>
                    <li>
                        <a  href="#">功能一</a>
                    </li>
                    <li>
                        <a  href="#">功能二</a>
                    </li>
                </ul>
            </div>

        </div>
    </div>
    
    <div class="pg-body">
        <div class="wrap">
            <div class="catalog">
                <div class="catalog-item" auto-to="function1"><a>第1張</a></div>
                <div class="catalog-item" auto-to="function2"><a>第2張</a></div>
                <div class="catalog-item" auto-to="function3"><a>第3張</a></div>
            </div>
            
            <div class="content">
                <div menu="function1" class="section" style='background-color:green;'>
                    <h1>第一章</h1>
                </div>
                <div menu="function2" class="section" style='background-color:yellow;'>
                    <h1>第二章</h1>
                </div>
                <div menu="function3" class="section" style='background-color:red;'>
                    <h1>第三章</h1>
                </div>
            </div>
        </div>

    </div>

    <script type="text/javascript" src="jquery-1.8.2.min.js"></script>
    <script type="text/javascript">
        
        $(function(){
            // 自動執行
            Init();
        });
        
        
        function Init(){
        
            
            $(window).scroll(function() {
                // 監聽窗口滾動事件
                
                
                // 獲取滾動條高度
                var scrollTop = $(window).scrollTop();
                
                
                // 當滾動到50像素時,左側帶菜單固定
                if(scrollTop > 50){
                    $('.catalog').addClass('fixed');
                }else{
                    $('.catalog').children().removeClass('active');
                    $('.catalog').removeClass('fixed');
                }

                // 循環全部的內容
                $('.content').children().each(function(){
                    // 當前標籤距離頂部高度
                    var offSet = $(this).offset(); // 高度,左邊有多遠
                    // offSet.top 
                    // offSet.left
                    
                    // 自身高度
                    var height = $(this).height();
                    
                    //offSet<滾動高度<offSet+height
                    

                    // 當前內容位於用戶閱覽區
                    if(scrollTop>offSet.top && scrollTop< offSet.top + height){
                        // $(this) 當前內容標籤
                        /*
                        var target = $(this).attr('menu');
                        $('.catalog').find('div[auto-to="'+target+'"]').addClass('active').siblings().removeClass('active');
                        return false;
                        */
                        
                        var docHeight = $(document).height();
                        var winHeight = $(window).height();
                        // 若是,滾輪到達底部,則顯示最後一個菜單
                        if(docHeight == winHeight+scrollTop)
                        {
                            $('.catalog').find('div:last-child').addClass('active').siblings().removeClass('active');
                        }else{
                            var target = $(this).attr('menu');
                            $('.catalog').find('div[auto-to="'+target+'"]').addClass('active').siblings().removeClass('active');
                        }
                        return false;
                        
                    }
                });

            });


        }

    </script>
</body>
</html>
View Code

總結:

jQuery示例:
    表單驗證,jQuery擴展
    一、回顧基礎內容
    
    二、dom事件綁定
    
    三、jquery事件綁定
    
    四、$.each     return false 表示break;
    
    五、jquery擴展方法:
        兩種方式:
            
    六、自定義jQuery擴展的正確方法:
        a. 自執行
        b. 閉包
    
    七、jquery擴展實現基本驗證
    
        a. 支持是否容許爲空
        
        b. 長度
        
        c. 正則表達式
            定義正則表達式
                reg = /正則表達式/  *****
                g
                i
                m ==> 特殊
                
            利用正則匹配
                reg.test(字符串)   *****
                reg.exec(字符串)
                    全局
                    非全局
            字符串三個方法:
                search
                match
                replace
                    -- 特殊符號

    滾動菜單
        頁面佈局(absolute)
        監聽滾動事件:
            若是滾動>60,菜單固定
            若是滾動<60,菜單固定取消
    
前端插件:
    fontawsome
    
    easyui    
    jqueryui
    bootstrap
    -- 引入css
    
    -- 引入jQuery(2.x,1.12)
    -- 引入js

    -- bootstrap模版
    
    bxslider
    jquery.lazyload
View Code

4、WEB框架

#!/usr/bin/env python
#coding:utf-8
  
import socket
  
def handle_request(client):
    buf = client.recv(1024)
    client.send("HTTP/1.1 200 OK\r\n\r\n")
    client.send("Hello, Seven")
  
def main():
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind(('localhost',8000))
    sock.listen(5)
  
    while True:
        connection, address = sock.accept()
        handle_request(connection)
        connection.close()
  
if __name__ == '__main__':
    main()
View Code

WSGI(Web Server Gateway Interface)是一種規範,它定義了使用python編寫的web app與web server之間接口格式,實現web app與web server間的解耦。

python標準庫提供的獨立WSGI服務器稱爲wsgiref。

經過python標準庫提供的wsgiref模塊開發一個本身的Web框架

#!/usr/bin/env python
#coding:utf-8
from wsgiref.simple_server import make_server
 
def index():
    return 'index'
 
def login():
    return 'login'
 
def routers():
     
    urlpatterns = (
        ('/index/',index),
        ('/login/',login),
    )
     
    return urlpatterns
 
def RunServer(environ, start_response):
    start_response('200 OK', [('Content-Type', 'text/html')])
    url = environ['PATH_INFO']
    urlpatterns = routers()
    func = None
    for item in urlpatterns:
        if item[0] == url:
            func = item[1]
            break
    if func:
        return func()
    else:
        return '404 not found'
     
if __name__ == '__main__':
    httpd = make_server('', 8000, RunServer)
    print "Serving HTTP on port 8000..."
    httpd.serve_forever()
View Code

框架demo

#!/usr/bin/env python
#coding:utf-8
# Author: wanghuafeng

from wsgiref.simple_server import make_server

def i1():
    return 'i1'

def i2():
    return 'i2'

def RunServer(environ, start_response):
    start_response('200 OK', [('Content-Type', 'text/html')])
    #獲取用戶url,根據用戶url響應不一樣內容
    #environ,封裝了用戶全部請求內容
    #路由系統
    if environ.url == 'index':
        return i1()
    elif environ.url == 'login':
        return i2()
    else:
        return "404"

    return '<h1>Hello,Web!</h1>'
if __name__ == '__main__':
    httpd = make_server('', 8000, RunServer)    #IP、端口、函數名
    print("Serving HTTP on port 8000...")
    httpd.serve_forever()
View Code
處理用戶請求      放置HTML模板           操做數據庫
 Controller      Views                 Models
 MVC框架

Views            Template              Models
 MTV框架

5、Django

一、安裝Django

python -m pip install django 
python3 -m pip install django
添加環境變量
C:\SourceForge\Python35\Lib\site-packages\django\bin

二、建立Project

django-admin startproject D:\Django\mysite

mysite目錄

mysite
    - settings.py    #配置文件
    - urls.py        #路由系統
    - wsgi.py        #WSGI
    - manage.py      #django程序啓動文件

三、建立APP(一個Project下能夠建立多個APP)

cd mysite
python3 manage.py startapp cmdb

四、配置路由映射和服務請求

from django.conf.urls import url
from django.contrib import admin
from cmdb import views

urlpatterns = [
    #url(r'^admin/', admin.site.urls),
    url(r'^index/', views.index),
]
urls.py
from django.shortcuts import render
from django.shortcuts import HttpResponse
# Create your views here.
def index(request):
    return HttpResponse('123')
views.py

五、啓動Django程序

python3 manage.py runserver 127.0.0.1:8000

訪問:http://127.0.0.1:8000/index/

顯示:123

六、返回html

templates中建立index.html

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1 style="color: red;font-size: 50px;">Django</h1>
</body>
</html>
index.html
from django.shortcuts import render
from django.shortcuts import HttpResponse
# Create your views here.
def index(request):
    #return HttpResponse('123')
    return render(request,'index.html')
views.py

七、靜態文件配置

建立statics目錄將jquery-1.8.2.min.js文件放置到該目錄

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1 style="color: red;font-size: 50px;">Django</h1>
    <script src="/fff/jquery-1.8.2.min.js"></script>
</body>
</html>
index.html
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/

#靜態文件引入時的前綴
STATIC_URL = '/fff/'
#靜態文件目錄
STATICFILES_DIRS = (
    os.path.join(BASE_DIR,'statics'),
)
settings.py

八、模板引擎

from django.shortcuts import render
from django.shortcuts import HttpResponse
# Create your views here.

#先設置默認值
USER_INPUT = [
    {'user':'u1','email':'e1'},
    {'user':'u2','email':'e2'},
]
def index(request):

    #判斷用戶是不是POST請求
    if(request.method == 'POST'):
        user = request.POST.get('user',None)
        email = request.POST.get('email',None)
        #print(user, email)
        temp = {'user':user,'email':email}
        #將用戶輸入的數據加入全局列表中
        USER_INPUT.append(temp)
        #request.POST.get('pwd',None)
    #return HttpResponse('123')
    #模板引擎
    #獲取index.html模板 + {'data' : USER_INPUT} ==》渲染(把for循環轉換爲python的for循環)
    #最終獲得一個替換完成的字符串
    return render(request,'index.html',{'data' : USER_INPUT})
views.py
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>用戶輸入:</h1>
    <form action="/index/" method="POST">
        <input type="text" name="user">
        <input type="text" name="email">
        <input type="submit" value="提交">
    </form>
    <h1>數據展現:</h1>
    <table border="1">
        {% for item in data %}
            <tr>
                <td>{{ item.user }}</td>
                <td>{{ item.email }}</td>
            </tr>
        {% endfor %}
    </table>
    <script src="/fff/jquery-1.8.2.min.js"></script>
</body>
</html>
index.html

九、數據庫操做

from django.db import models

# Create your models here.
class UserInfo(models.Model):
    #字符串類型必須指定長度
    user = models.CharField(max_length=32)
    email = models.CharField(max_length=32)
models.py

執行命令建立數據庫表結構:

python3 manage.py makemigrations
python3 manage.py migrate

註冊APP

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    #註冊APP
    'cmdb',
]
settings.py
from django.shortcuts import render
from django.shortcuts import HttpResponse
from cmdb import models
# Create your views here.

def index(request):

    #判斷用戶是不是POST請求
    if(request.method == 'POST'):
        u = request.POST.get('user',None)
        e = request.POST.get('email',None)
        #添加數據到數據庫
        models.UserInfo.objects.create(user=u, email=e)


    #獲取數據庫的數據
    data_list = models.UserInfo.objects.all()
    #[UserInfo對象,UserInfo對象,UserInfo對象,UserInfo對象,...]
    # for item in data_list:
    #     print(item.user,item.email)
    return render(request,'index.html',{'data':data_list})
views.py

從新啓動服務,登陸訪問:http://127.0.0.1:8000/index

十、總結

安裝:
        python -m pip install django 
        python3 -m pip install django
        添加環境變量
        C:\SourceForge\Python35\Lib\site-packages\django\bin
        
    1、建立mysite項目
    django-admin startproject D:\Django\mysite
    mysite
        mysite
            - settings.py    #配置文件
            - urls.py    #路由系統
            - wsgi.py    #WSGI
        manage.py    #django程序啓動文件

    2、建立APP
    cd mysite
    python3 manage.py startapp cmdb

    3、編寫代碼
     urls.py
     view.py 函數

    4、啓動Django程序
     python3 manage.py runserver 127.0.0.1:8000

    5、使用模板
     settings配置
     render(request,'路徑')

    6、靜態文件的配置(自定義目錄)
     STATIC_URL = 'fff'
     STATICFILES_DIRS = (
         os.path.join(BASE_DIR,'statics'),
     )
     statics目錄放置靜態文件
     <script src="/fff/jquery-1.8.2.min.js"></script>

    CSRF:跨棧請求僞造

    7、ORM
    models.py
    from django.db import models

    # Create your models here.
    class UserInfo(models.Model):
        #字符串類型必須指定長度
        user = models.CharField(max_length=32)
        email = models.CharField(max_length=32)

    註冊APP
    # Application definition

    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        #註冊APP
        'cmdb',
    ]

    執行命令:
    python3 manage.py makemigrations
    python3 manage.py migrate
    ====>數據庫已建立

    8、操做數據庫
    建立:
         models.類.objects.create(user=u, email=e)
         models.類.objects.create(user=u, email=e)
         models.類.objects.create(user=u, email=e)
         models.類.objects.create(user=u, email=e)
    操做:
        models.類.objects.all()
相關文章
相關標籤/搜索