python day18

 

Web框架
    请求周期
    处理用户请求       放置HTML模版        操作数据库
    Controllers         Views               Modals
   
      Views             Template            Modals
   
    MVC/MTV
   
   
    Django => MTV   
   
Django       
    1.安装
        pip3 install Django==1.10    或  pip3 install Django
       
    2.创建project
        django-admin.py startproject mysite
        目录结构
            mysite  
                mysite   
                    - settings.py    # 配置文件
                    - urls.py          # 路由系统(调度)
                    - wsgi.py         # WSGI
                managel.py              # django程序启动文件
       
    3.创建APP
        所有APP共享project
            cd mysite
            python3 manage.py startapp cmdb
       
        cmdb
            __init__.py
            admin.py            # WEB后台管理
            apps.py                # 当前app配置文件
            models.py            # 数据库管理,自动创建数据结构
            tests.py            # 单元测试,测试你的某个功能
            views.py            # 业务请求处理
           
       
       
   
    4.编写代码
        urls.py
        views.py
            (1) 配置路由关系  urls.py
            urls.py       
                from cmdb import views                                 #导入views模块
                urlpatterns = [
                    # url(r'^admin/', admin.site.urls),   
                    url(r'^index/', views.index),                      # 配置映射关系,逗号前是url,逗号后为交给某一函数(view模块的index函数)
                ]
           
            (2) 配置业务请求处理 views.py
            views.py  创建对应自己的函数
                cmdb  的 views 处理用户请求,必须为函数
                    from django.shortcuts import HttpResponse          # 导入处理模块
                    # Create your views here.
                    # 处理用户请求
                    def index(request):                                   # 处理函数,用户请求放入request中
                        return HttpResponse('123')                  # 处理字符串,必须放在HttpResponse才能识别
       
    5.启动Django程序
        python3 manage.py runserver 8000
        python manage.py runserver  #测试  启动web服务器,只允许本地访问
        python manage.py runserver 0.0.0.0:8080  #允许所有
       
       
       
    6.访问
        http://127.0.0.1:8000/index/
       
       
       
    7.使用模板
        settings配置
            指定Template目录,告诉django配置文件在那里
        render传递数据给html (request,'路径')
       
        (1)    Template                    # 放置HTML模版,可新建
                index.html                # 手动创建
                    <!DOCTYPE html>
                    <html lang="en">
                    <head>
                        <meta charset="UTF-8">
                        <title>Title</title>
                    </head>
                    <body>
                        <h1 style="color: red">123</h1>
                    </body>
                    </html>
           
        (2)    views           #配置业务请求处理,指定html文件,在cmdb目录下
                from django.shortcuts import render
                def index(request):
                # return HttpResponse('123')
                return render(request,'index.html')       #使用render方法指定html
           
       
        (3) 启动并访问
            python manage.py runserver 0.0.0.0:8080
            http://127.0.0.1:8000/index/
   
   
    8. 静态文件配置
        (1) statics             # 手动创建,在mysite主目录创建
            jquery-1.8.2.min.js     # 存入jquery文件
       
        (2) index.html 指定statics
            <script src="/statics/jquery-1.8.2.min.js"></script>
       
        (3) settings 指定statics,在文件最后添加
            (1) 指定静态文件目录
                STATICFILES_DIRS = (
                    os.path.join(BASE_DIR,'statics'),
                )
                       
            (2)    指定HTML引用静态文件的前缀,可选项,非必选
                STATIC_URL = '/fff/'        #指定前缀为fff

        (4) index.html 引用前缀
            <script src="/fff/jquery-1.8.2.min.js"></script>
           
        (5) 访问
            F12 --- Elements----/fff/jquery-1.1.8.2.min.js----右键---open link in new tab打开成功即可
           

                   
    9.表单操作及页面展示(内存版)
        (1)表单页面
            <body>
                <h1>用户输入:</h1>
                {#以POST方式提交#}
                <form action="/index/" method="POST">
                    <input type="text" name="user"/>
                    <input type="test" name="email"/>
                    <input type="submit" value="提交"/>
                </form>
            </body>
       
       
        (2)views处理
            # 判断用户是否是POST请求
            from django.shortcuts import render
            from django.shortcuts import HttpResponse
            # Create your views here.

            def index(request):
                # return HttpResponse('123')
                # 判断
                if (request.method == 'POST'):
                    user = request.POST.get('user', None)
                    email = request.POST.get('email', None)
                    print(user, email)
                return render(request,'index.html')
           
            直接访问会提交会报错,是DJANGO提供的跨站请求伪造,可以通过settings修改处理
                Forbidden (403)
                CSRF verification failed. Request aborted.
           
           
           
        (3)settings修改
            MIDDLEWARE 或 MIDDLEWARE-CLASSES 列表注释掉 django.middleware.csrf.CsrfViewMiddleware 这一行
                MIDDLEWARE = [
                    'django.middleware.security.SecurityMiddleware',
                    'django.contrib.sessions.middleware.SessionMiddleware',
                    'django.middleware.common.CommonMiddleware',
                    # 'django.middleware.csrf.CsrfViewMiddleware',           
                    'django.contrib.auth.middleware.AuthenticationMiddleware',
                    'django.contrib.messages.middleware.MessageMiddleware',
                    'django.middleware.clickjacking.XFrameOptionsMiddleware',
                ]
                               
        (4)页面提交
            提交内容为   123 123
            后台接收到数据
                123 123
                [31/Aug/2016 23:13:28] "POST /index/ HTTP/1.1" 200 339
           
           
           
        (5)数据展示
            (1)views 处理数据   
                from django.shortcuts import render
                from django.shortcuts import HttpResponse
                # 1. 处理用户请求   u1和e1为两列,u1和u2为两行
                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)
                        temp = {'user': user, 'email': email}
                        USER_INPUT.append(temp)             # 2. 追加到列表
                        # request.POST.get('pwd',None)

                    # return HttpResponse('123')
                    # 模版引擎
                    # 获取index.html模版 + {'data': USER_INPUT } ==》 渲染
                    # 字符串

                    #传递给HTML
                    return render(request, 'index.html', {'data': USER_INPUT })       # 3. 传递给HTML使用data指定USER_INPUT列表
                           
           
           
            (2)HTML 编写代码,按django方式对数据进行for循环生成列表(取的是views里的data和USER_INPUT数据)
                django的for循环必须有开始有结束{% for item in data %}, {% endfor %}
                <!DOCTYPE html>
                <html lang="en">
                <head>
                    <meta charset="UTF-8">
                    <title>Title</title>
                </head>
                <body>
                    <h1>用户输入:</h1>
                    {#以POST方式提交#}
                    <form action="/index/" method="POST">
                        <input type="text" name="user"/>
                        <input type="test" name="email"/>
                        <input type="submit" value="提交"/>
                    </form>

                    <h1>数据展示:</h1>
                   
                    <table border="1">
                        {% for item in data %}
                        {# tr为行,td为列#}
                            <tr>
                                <td>{{ item.user }}</td>
                                <td>{{ item.email }}</td>
                            </tr>
                        {% endfor %}
                    </table>
                   
                    <script src="/fff/jquery-1.8.2.min.js"></script>
                   
                </body>
                </html>
           
               
                页面初始列表样式
                    ----
                   |u1|e1|
                   |---|
                   |u2|e2|
                    ----   
               
           
            (3)提交数据到内存,输入内容后提交后在表格显示
                http://127.0.0.1:8000/index/
           
           
    10.连接数据库
        默认使用sqlite数据库
        ORM  数据结构管理  models.py
        settings
       
       
        (1)models.py       #配置数据库,创建类,生成数据库UserInfo表,指定字符长度
            class UserInfo(models.Model):
                user = models.CharField(max_length=32)
                email = models.CharField(max_length=32)
               
        (2)注册app:
            settings.py    # 指定APP名字
                INSTALLED_APPS = [
                    'django.contrib.admin',
                    'django.contrib.auth',
                    'django.contrib.contenttypes',
                    'django.contrib.sessions',
                    'django.contrib.messages',
                    'django.contrib.staticfiles',
                    'cmdb',                          
                ]
       
        (3)执行命令,创建库和表
            python3 manage.py makemigrations
            python3 manage.py migrate
            两条命令完自动创建UserInfo表
           
            返回结果:
                makemigrations返回结果
                    Migrations for 'cmdb':
                    cmdb\migrations\0001_initial.py:
                    - Create model UserInfo
                migrate返回结果
                    Applying cmdb.0001_initial... OK
                    Applying sessions.0001_initial... OK
                   
                   
    11.操作数据库   
        创建:
            models.类.objects.create(user=u,email=e)
            models.UserInfo.objects.create(user=u,email=e)
            models.UserInfo.objects.create(user=u,email=e)
            models.UserInfo.objects.create(user=u,email=e)
        获取:
            models.类.objects.all()
            models.UserInfo.objects.all()
   
   
   
        (1)views 处理
            from django.shortcuts import render
            from django.shortcuts import HttpResponse
            from django.shortcuts import redirect
            from cmdb import models                                                  # 1.导入models数据库模块
            # 处理用户请求

            def index(request):
                # ...
                # 判断用户是否是POST请求
                # return redirect('http://baidu.com')
                # return redirect('')
                if(request.method == 'POST'):
                    u = request.POST.get('user',None)
                    e = request.POST.get('email',None)
                    models.UserInfo.objects.create(user=u,email=e)                   # 2. Post提交数据,使数据库出现内容
                    # request.POST.get('pwd',None)

                # return HttpResponse('123')
                # 模版引擎
                # 获取index.html模版 + {'data': USER_INPUT } ==》 渲染
                # 字符串

                data_list = models.UserInfo.objects.all()                            # 3. 取UserInfo表数据,get取数据,对于ORM每一行数据都是它的对像
                # [UserInfo对象,UserInfo对象,。。。]   每一行数据里都是一个对像
                # for item in data_list:
                #     print(item.user,item.email)
                #传递给HTML
                return render(request, 'index.html', {'data': data_list })           # 4. 传递给HTML使用data_list指定USER_INPUT列表

       
        (2)HTML文件
            index.html  循环data_list,取每一行对像数据
                <!DOCTYPE html>
                <html lang="en">
                <head>
                    <meta charset="UTF-8">
                    <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">
                        <tr>
                            <th>用户名</th>
                            <th>邮箱</th>
                        </tr>
                        {% for line in data %}
                            <tr>
                                <td>{{ line.user }}</td>
                                <td>{{ line.email }}</td>
                            </tr>
                        {% endfor %}
                    </table>


                    <script src="/fff/jquery-1.8.2.min.js"></script>
                </body>
                </html>
           
       
        (3)访问提交数据到库
            http://127.0.0.1:8000/index/
       
       
       
       
       
       
       
django-admin.py startproject mysite


python3 manage.py startapp app1

一、路由系统     
二级页面      对应urls函数
urls.py       views.py    

from app1  import views


1.  配置路由系统urls.py

from app1  import views

urlpatterns = [
    # url(r'^admin/', admin.site.urls),
    url(r'^index/', views.f1),
    url(r'^login/', views.login),
    url(r'^detail/(\d+)/', views.detail),
    url(r'^detail2/(\d+)/(\d+)/', views.detail2),
    url(r'^detail2/(?P<p1>\d+)/(?P<x2>\d+)/', views.detail3),
]

 

2. 业务处理 views.py


from django.shortcuts import HttpResponse

def f1(request):
    return HttpResponse('OK')

def login(request):
    return HttpResponse('OK')


def detail(request,nid):
    print(nid)
    return HttpResponse('OK')


# detail2(1,2)
def detail2(request,xid,nnid):
    print(xid,nnid)
    return HttpResponse('OK')

# detail3(x2=234,p1=123)
def detail3(request,p1,x2):
    print(p1,x2)
    return HttpResponse('OK')

 

3.页面访问

http://127.0.0.1:8000/login/
http://127.0.0.1:8000/detail/123/
http://127.0.0.1:8000/detail2/123/12313/

 

 

 

 

 

分页查看,资源信息管理


   
1.路由系统
   
--------urls.py

from app1  import views

urlpatterns = [
    # url(r'^admin/', admin.site.urls),
    # url(r'^index/', views.f1),
    # url(r'^login/', views.login),
    # url(r'^detail/(\d+)/', views.detail),
    # url(r'^detail2/(\d+)/(\d+)/', views.detail2),
    # url(r'^detail3/(?P<p1>\d+)/(?P<x2>\d+)/', views.detail3),
    url(r'^index/(\d+)/', views.index),
    url(r'^detail/(\d+)/', views.detail),
]

 


2.业务函数处理

-------views.py  

USER_LIST = []
for item in range(94):
    temp = {"id":item,'username':'alex'+str(item),'email':'email'+str(item)}
    USER_LIST.append(temp)

def index(request,page):
    print(page)
     # 1,0-9
     # 2,10-19
     # 3,20-29
    page = int(page)
    start = (page-1) * 10
    end = page * 10
    user_list = USER_LIST[start:end]
    # return HttpResponse('OK')
    return render(request,'index.html',{'user_list':user_list})


def detail(request,nid):
    nid = int(nid)
    current_detail_dict = USER_LIST[nid]
    return render(request,'detail.html',{'current_detail_dict':current_detail_dict})

 

 

 

 


3.两个html

--------index.html


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <table>
        <tr>
            <td>ID</td>
            <td>用户名</td>
            <td>详细</td>
        </tr>
        {% for item in user_list %}
            <tr>
                <td>{{ item.id }}</td>
                <td>{{ item.username }}</td>
                <td><a href="/detail/{{ item.id }}/">查看详细</a></td>
            </tr>
        {% endfor %}
    </table>
</body>
</html>

 

 

 


--------detail.html


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <ul>
        <li>
            {{ current_detail_dict.id }}
        </li>
        <li>
            {{ current_detail_dict.username }}
        </li>
         <li>
            {{ current_detail_dict.email }}
        </li>
    </ul>
</body>
</html>

 

 

 

 

4. 页面访问

http://127.0.0.1:8000/index/1/   或 http://127.0.0.1:8000/index/22/


ID    用户名    详细
0    alex0    查看详细
1    alex1    查看详细
2    alex2    查看详细
3    alex3    查看详细
4    alex4    查看详细
5    alex5    查看详细
6    alex6    查看详细
7    alex7    查看详细
8    alex8    查看详细
9    alex9    查看详细

点击“详细信息”

http://127.0.0.1:8000/detail/0/

0
alex0
email0

 

 


自定义方法
    filter                  # 过滤
    simple_tag                # 帮助标签
   

   
    1.创建指定文件,名称不能改 templatetags
    2.创建任意.py 文件,如:xx.py
        from django import template
        from django.utils.safestring import mark_safe
        # from django.template.base import resolve_variable,Node,TemplateSyntaxError
        # from django.template.base import Node,TemplateSyntaxError
       
        # 必须不变
        register = template.Library()

        # 创建函数
        @register.filter
        def f1(value,arg):
            return value + "666" + arg


        @register.simple_tag
        def f2(s1,s2,s3,s4):
            return s1 + s2 + s3 + s4


        @register.filter
        def f3(value):
            if value == 'VVV':
                return True
            return False

    3.在html模板头部执行
        加入此内容   {% load xx %}
    mysite/template.html
        {% load xx %}
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <title>Title</title>
        </head>
        <body>
            {{ k1 }}
            {{ k2.1 }}

            {% for item in k2 %}
                <p>{{ item }},{{ forloop.counter }},{{ forloop.counter0 }},{{ forloop.first }},{{ forloop.last }},{{ forloop.revcounter }}</p>
            {% endfor %}

            {% if k1 == 'v1' %}
                <h1>V1</h1>
            {% elif k1 == 'v2' %}
                <h1>V2</h1>
            {% else %}
                <h1>7777</h1>
            {% endif %}
            {{ k1 }}
            {{ k1|lower }}
            {{ k1|f1:"alex" }}
            {%  if k1|f3 %}
                <h1>True</h1>
            {% else %}
                <h1>False</h1>
            {% endif %}
        </body>
        </html>

    4. setting.py 中注册app
        INSTALLED_APPS = [
            'django.contrib.admin',
            'django.contrib.auth',
            'django.contrib.contenttypes',
            'django.contrib.sessions',
            'django.contrib.messages',
            'django.contrib.staticfiles',
            'app1'
        ]


    5. views.py
        from django import template
        from django.utils.safestring import mark_safe
        # from django.template.base import resolve_variable,Node,TemplateSyntaxError
        from django.template.base import Node,TemplateSyntaxError

        register = template.Library()

        @register.filter
        def f1(value, arg):
            return value + "666" + arg

        @register.simple_tag
        def f2(s1,s2,s3, s4):
            return s1 + s2 + s3 + s4

        @register.filter
        def f3(value):
            if value == 'VVV':
                return True
            return False

        @register.simple_tag
        def f4(value):
            if value == 'VVV':
                return True
            return False

 


    6.app1创建urls.py
        from django.conf.urls import url
        from django.contrib import admin

        #路由系统
        from app1 import views

        urlpatterns = [
            # url(r'^index/(\d+)/', views.index),
            # url(r'^detail/(\d+)/', views.detail),
            url(r'^template/', views.template),
        ]

       
    7.myste的urls.py
        from django.conf.urls import url,include       #想自定义必须使用include

        urlpatterns = [
            # url(r'^admin/', admin.site.urls),
            # url(r'^index/', views.f1),
            # url(r'^login/', views.login),
            # url(r'^detail/(\d+)/', views.detail),
            # url(r'^detail2/(\d+)/(\d+)/', views.detail2),
            # url(r'^detail3/(?P<p1>\d+)/(?P<x2>\d+)/', views.detail3),
            # url(r'^index/(\d+)/', views.index),
            # url(r'^detail/(\d+)/', views.detail),
            url(r'^web/', include('app1.urls')),
        ]
       
    8. mysite的apps.py
        from django.apps import AppConfig
        class App1Config(AppConfig):
            name = 'app1'

       

    9.页面访问
    http://127.0.0.1:8000/web/template/
        VVVV 22
        11,1,0,True,False,3

        22,2,1,False,False,2

        33,3,2,False,True,1

        7777

        VVVV vvvv VVVV666alex
        False

 

 

 

 


后台管理系统,block模板使用
    views.py
        def assets(request):
            assets_list = []
            for i in range(10):
                temp = {'hostname':'h1'+str(i),'port':80}
                assets_list.append(temp)
            return render(request,'assets.html',{'assets_list':assets_list})


        def userinfo(request):
            user_list = []
            for i in range(10):
                temp = {'username':'h1'+str(i),'salary':80}
                user_list.append(temp)
            return render(request,'userinfo.html',{'user_list':user_list})
           
           
           
    mysite/apps.py
        urlpatterns = [
        url(r'', include('app1.urls')),
        ]
   
    app1/urls.py
        from app1  import views
        urlpatterns = [
            # url(r'^index/(\d+)/', views.index),
            # url(r'^detail/(\d+)/', views.detail),
            url(r'^assets', views.assets),
            url(r'^userinfo', views.userinfo),
        ]

       
    template/
        assets.html
            {% extends 'layout.html' %}

            {% block body %}
                <table>
                    {% for item in assets_list %}
                        <tr>
                            <td>{{ item.hostname }}</td>
                            <td>{{ item.port }}</td>
                        </tr>
                    {% endfor %}
                </table>
            {% endblock %}

        layout.html
            <!DOCTYPE html>
            <html lang="en">
            <head>
                <meta charset="UTF-8">
                <title></title>
                <link rel="stylesheet" href="..." />
                <style>
                    .pg-header{
                        height: 48px;
                        background-color: cadetblue;
                    }
                    .pg-body{
                        min-height: 500px;
                    }
                    .pg-body .body-menu{
                        width: 20%;
                        float: left;
                    }
                    .pg-body .body-content{
                        width: 80%;
                        float: left;
                    }
                    .pg-footer{
                        height: 100px;
                        background-color: brown;
                    }
                    .active{
                        background-color: aquamarine;
                        color: white;
                    }
                </style>

                {% block css %}{% endblock %}
            </head>
            <body>
                <div class="pg-header">
                    后台系统V1
                </div>
                <div class="pg-body">
                    <div class="body-menu">
                        <ul>
                            <li><a href="/userinfo">用户管理</a></li>
                            <li><a href="/assets">资产管理</a></li>
                        </ul>
                    </div>
                    <div class="body-content">
                        {% block body %}{% endblock %}
                    </div>

                </div>
                <div class="pg-footer"></div>
                <script src="xxx"></script>
                {% block js %}{% endblock %}
            </body>
            </html>
           
        userinfo.html
            {% extends 'layout.html' %}

            {% block css %}
                <style></style>
            {% endblock %}

            {% block body %}
                <ul>
                {% for item in user_list %}
                    <li>{{ item.username }},{{ item.salary }}</li>
                {% endfor %}
                </ul>

            {% endblock %}

            {% block js %}

            {% endblock %}       
           
    访问
        http://127.0.0.1:8000/userinfo
        http://127.0.0.1:8000/assets
       

 

       
       
AJAX使用    http://www.cnblogs.com/wupeiqi/articles/5703697.html
创建交互式网页应用的网页开发技术
    作用:
        1、注册时,输入用户名自动检测用户是否已经存在。
        2、登陆时,提示用户名密码错误
        3、删除数据行时,将行ID发送到后台,后台在数据库中删除,数据库删除成功后,在页面DOM中将数据行也删除。(博客园)

   
ajax_demo
    urls.py   
        from django.conf.urls import url,include
        urlpatterns = [
            # url(r'^admin/', admin.site.urls),
            # url(r'^index/', views.f1),
            # url(r'^login/', views.login),
            # url(r'^detail/(\d+)/', views.detail),
            # url(r'^detail2/(\d+)/(\d+)/', views.detail2),
            # url(r'^detail3/(?P<p1>\d+)/(?P<x2>\d+)/', views.detail3),
            # url(r'^index/(\d+)/', views.index),
            # url(r'^detail/(\d+)/', views.detail),
            url(r'^web/', include('app1.urls')),
        ]
   
    views.py
        def ajax_demo(request):
        if request.method == 'POST':
            user = request.POST.get('user',None)
            pwd = request.POST.get('pwd',None)
            if user == '111' and pwd == '222':
                return HttpResponse('1')
            else:
                return HttpResponse('2')
        return render(request,'ajax_demo.html')

   
    app1/urls.py
        from django.conf.urls import url
        from django.contrib import admin

        #路由系统
        from app1 import views

        urlpatterns = [
            # url(r'^index/(\d+)/', views.index),
            # url(r'^detail/(\d+)/', views.detail),
            # url(r'^template', views.template),
            url(r'^assets', views.assets),
            url(r'^userinfo', views.userinfo),
            url(r'^ajax_demo', views.ajax_demo),
        ]

   
   
    settings.py
        STATIC_URL = '/static/'
        STATICFILES_DIRS = (
            os.path.join(BASE_DIR, 'static'),
        )

       
        INSTALLED_APPS = [
            'django.contrib.admin',
            'django.contrib.auth',
            'django.contrib.contenttypes',
            'django.contrib.sessions',
            'django.contrib.messages',
            'django.contrib.staticfiles',
            'ajax_demo'
        ]
       
       
        注释
        MIDDLEWARE = [
            'django.middleware.security.SecurityMiddleware',
            'django.contrib.sessions.middleware.SessionMiddleware',
            'django.middleware.common.CommonMiddleware',
            # 'django.middleware.csrf.CsrfViewMiddleware',
            'django.contrib.auth.middleware.AuthenticationMiddleware',
            'django.contrib.messages.middleware.MessageMiddleware',
            'django.middleware.clickjacking.XFrameOptionsMiddleware',
        ]
           
   
    创建static,加jquery
        static/jquery-1.8.2.min.js


   
    创建页面templates/ajax_demo.html
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <title></title>
        </head>
        <body>
            <div>
                <p>用户名:<input type="text" id="username" /></p>
            </div>
            <div>
                <p>密码:<input type="password" id="pwd" /></p>
            </div>
            <input type="button" value="提交" onclick="SubmitForm();" />

            <script src="/static/jquery-1.8.2.min.js"></script>

            <script>
                function SubmitForm(){
                    $.ajax({
                        url: '/web/ajax_demo/',
                        type: 'POST',
                        data: {'user': $('#username').val(), 'pwd': $('#pwd').val()},
                        success: function (data) {
                            if(data == '1'){
                                location.href = "http://www.baidu.com";
                            }else{
                                alert('用户名或密码错误')
                            }
                        }
                    })
                }
            </script>
        </body>
        <html>
           
   
    页面访问
        http://127.0.0.1:8000/web/ajax_demo
   
   
   
   
   
    规定响应数据格式
        views.py
            import json
            def ajax_demo(request):
                if request.method == 'POST':
                    ret = {'status':False,'message':''}
                    user = request.POST.get('user',None)
                    pwd = request.POST.get('pwd',None)
                    if user == '111' and pwd == '222':
                        ret['status'] = True
                        return HttpResponse(json.dumps(ret))
                    else:
                        ret['message'] = "用户名或密码错误"
                        return HttpResponse(json.dumps(ret))
                return render(request,'ajax_demo.html')
               
       
        ajax_demo.html
            <script>
                function SubmitForm(){
                    $.ajax({
                        url: '/web/ajax_demo/',
                        type: 'POST',
                        data: {'user': $('#username').val(), 'pwd': $('#pwd').val()},
                        dataType:'json',
                        success: function (data) {
                            if(data.status){
                                location.href = "http://www.baidu.com";
                            }else{
                                alert('data.message');
                            }
                        }
                    })
                }
            </script>
           
       
       
        页面访问
            http://127.0.0.1:8000/web/ajax_demo
           
            输入 111  密码 222 跳百度
            输入错误 提错
       
       
       
       
       
DJANGO-ADMIN后台使用       
model,ORM

    1、创建(CURD)数据库表
            class -> DB,表
            DB,表 -> 类
           
            a. app.models.py写类
                from django.db import models
     
                class userinfo(models.Model):
                    name = models.CharField(max_length=30) # string
                    email = models.EmailField()            # string,帮助admin做输入验证,modelform
                    memo = models.TextField()              # text
           
           
            b. python manage.py makemigrations
               python manage.py migrate
       
               python manage.py createsuperuser
              

 


        model.py
            class userinfo(models.Model):
                nid = models.AutoField(primary_key=True)
                name = models.CharField(max_length=30)
                email = models.EmailField()
                memo = models.TextField()
                img = models.ImageField()
                user_type = models.ForeignKey("UserType",null=True,blank=True)

            class UserType(models.Model):
                name = models.CharField(max_length=32)
                def __str__(self):
                    return self.name
                   
        urls.py
            urlpatterns = [
                url(r'^admin/', admin.site.urls),
                # url(r'^index/', views.f1),
                # url(r'^login/', views.login),
                # url(r'^detail/(\d+)/', views.detail),
                # url(r'^detail2/(\d+)/(\d+)/', views.detail2),
                # url(r'^detail3/(?P<p1>\d+)/(?P<x2>\d+)/', views.detail3),
                # url(r'^index/(\d+)/', views.index),
                # url(r'^detail/(\d+)/', views.detail),
                url(r'^web/', include('app1.urls')),
            ]

           
        admin.py
            from app1 import models
            admin.site.register(models.userinfo)
            admin.site.register(models.UserType)

        pip3 install Pillow
        python3 manage.py makemigrations
        python3 manage.py migrate
        python3 manage.py createsuperuser    #用户名 wmh  密码 jlch@wmh123
   
   
        访问
            http://127.0.0.1:8000/admin/     #用户名 wmh  密码 jlch@wmh123
   

   
   
   
        2、操作数据库的数据
            类
                1、models.AutoField 自增列 = int(11)
                如果没有的话,默认会生成一个名称为 id 的列,如果要显示的自定义一个自增列,必须将给列设置为主键 primary_key=True。
                2、models.CharField 字符串字段
                必须 max_length 参数
                3、models.BooleanField 布尔类型=tinyint(1)
                不能为空,Blank=True
                4、models.ComaSeparatedIntegerField 用逗号分割的数字=varchar
                    input:  12,345,989871234,
               
                继承CharField,所以必须 max_lenght 参数
                5、models.DateField 日期类型 date
                对于参数,auto_now = True 则每次更新都会更新这个时间;auto_now_add 则只是第一次创建添加,之后的更新不再改变。
                6、models.DateTimeField 日期类型 datetime
                同DateField的参数
                7、models.Decimal 十进制小数类型 = decimal
                必须指定整数位max_digits和小数位decimal_places
                8、models.EmailField 字符串类型(正则表达式邮箱) =varchar
                对字符串进行正则表达式
                9、models.FloatField 浮点类型 = double
                10、models.IntegerField 整形
                11、models.BigIntegerField 长整形
                integer_field_ranges = {
                'SmallIntegerField': (-32768, 32767),
                'IntegerField': (-2147483648, 2147483647),
                'BigIntegerField': (-9223372036854775808, 9223372036854775807),
                'PositiveSmallIntegerField': (0, 32767),
                'PositiveIntegerField': (0, 2147483647),
                }
                12、models.IPAddressField 字符串类型(ip4正则表达式)
                13、models.GenericIPAddressField 字符串类型(ip4和ip6是可选的)
                参数protocol可以是:both、ipv4、ipv6
                验证时,会根据设置报错
                14、models.NullBooleanField 允许为空的布尔类型
                15、models.PositiveIntegerFiel 正Integer
                16、models.PositiveSmallIntegerField 正smallInteger
                17、models.SlugField 减号、下划线、字母、数字
                18、models.SmallIntegerField 数字
                数据库中的字段有:tinyint、smallint、int、bigint
                19、models.TextField 字符串=longtext
                20、models.TimeField 时间 HH:MM[:ss[.uuuuuu]]
                21、models.URLField 字符串,地址正则表达式
                22、models.BinaryField 二进制
               
                23、models.ImageField   图片    字符串
                24、models.FilePathField 文件   字符串


    models.py
        单表
            一对多 :Forigkey
            多对多: ManyToManyField
            一对一: ForeignKey 对 ForeignKey
           
           
            models.py       
           
                from django.db import models

                # Create your models here.


                # 陈超,普通用户
                # 淮军,超级用户
                class Gender(models.Model):
                    name = models.CharField(max_length=32)


                class userinfo(models.Model):
                    nid = models.AutoField(primary_key=True)
                    name = models.CharField(max_length=30, verbose_name='用户名',editable=False)
                    email = models.EmailField(db_index=True)
                    memo = models.TextField()
                    img = models.ImageField(upload_to='upload')
                    user_type = models.ForeignKey("UserType", null=True, blank=True)# unique
                    # user_type = models.OneToOneField("UserType", null=True, blank=True)# unique
                    # ctime = models.DateTimeField(auto_now_add=True)
                    # uptime = models.DateTimeField(auto_now=True)

                    # gender = models.ForeignKey(Gender)
                    # 性别选项
                    gender_choices = (        
                        (0, "男"),
                        (1, "女"),
                    )
                    gender = models.IntegerField(choices=gender_choices,default=1)

 

                # 普通用户,超级用户
                class UserType(models.Model):
                    name = models.CharField(max_length=32)

                    def __str__(self):
                        return self.name

                class B2G(models.Model):
                    boy = models.ForeignKey('Boy')
                    girl = models.ForeignKey('Girl')

                class Boy(models.Model):
                    name = models.CharField(max_length=32)
                # 吴文煜,王建,王志刚,杜宝强

                class Girl(models.Model):
                    name = models.CharField(max_length=32)

                    f = models.ManyToManyField(Boy)     #外键
                # 铁锤,钢弹,如花

                   
           

    独个获取
        obj = model.UserInfo.objects.filter(name='alex')
        print obj.query
       
        queryset -> python,Django的类
        [obj1,obj2,obj3]
       
        obj = model.UserInfo.objects.filter(name='alex').values('id','email')
        # select id from userinfo where name = 'alex'
       
        queryset -> python,Django的类
        [{'id':1},{'id': 2},]
       
        obj = model.UserInfo.objects.filter(name='alex').value_list('id','email')
        # select id from userinfo where name = 'alex'
       
        queryset -> python,Django的类
        [(1,'1@qq.com'),(2,'alex@11.com'),]
           
           
        queryset.query => SQL语句

posted @ 2016-09-09 22:32  颠覆自我  阅读(202)  评论(0编辑  收藏  举报