zoukankan      html  css  js  c++  java
  • Django基础续

    一.中间件

    django 中的中间件(middleware),在django中,中间件其实就是一个类,在请求到来和结束后,django会根据自己的规则在合适的时机执行中间件中相应的方法。

    在django项目的settings模块中,有一个 MIDDLEWARE_CLASSES 变量,其中每一个元素就是一个中间件。

    代码:

    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',
    ]
    View Code

     1.过程

    #可用于:1.黑名单  2.免登陆

    2.2.自定义中间件

    代码:

    1.注册中间件(settings.py)

    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',
        
        
        'm1.Middle1',
        'm1.Middle2',
    ]
    View Code

    2.创建中间件(m1.py:)

    from django.utils.deprecation import MiddlewareMixin
    
    from django.shortcuts import HttpResponse
    
    
    
    #中间件 一
    class Middle1(MiddlewareMixin):
        def process_request(self, request):
            print('m1.process_request')
            # return HttpResponse('不要在往下周了')
    
        def process_response(self, request, response):
            print('m1.process_response')
            return response
    
    
    #中间件 二
    class Middle2(MiddlewareMixin):
        def process_request(self, request):
            print('m2.process_request')
            # return HttpResponse('不要在往下周了')
    
        def process_response(self, request, response):
            print('m2.process_response')
            return response
    View Code

     执行结果:

     3.路由关系的匹配

    3.1.路由

    3.1.1单一路由

    rom django.conf.urls import url
    from django.contrib import admin
    
    from app01.views import love
    from app01.views import account
    
    urlpatterns = [
        
        
        url(r'^admin/', admin.site.urls),
    
        url(r'^login.html$',account.login),
        url(r'^logout.html$',account.logout),
    
        url(r'^index.html$',love.index),
        url(r'^others.html$',love.others),
    
    ]
    View Code

    3.1.2 基于正则的路由

    url(r'^index/(d*)', views.index),
    
    url(r'^manage/(?P<name>w*)/(?P<id>d*)', views.manage),
    

     3.1.3 添加额外的参数

    url(r'^manage/(?P<name>w*)', views.manage,{'id':333}),
    

     3.1.4为路由映射设置名称

    url(r'^home', views.home, name='h1'),
    
    url(r'^index/(d*)', views.index, name='h2'),
    

     3.1.5路由分发

    urls.py
                    url(r'^app01/', include('app01.urls')),
                
                app01.urls.py
                    url(r'^index.html$', views.index),
    View Code

    3.2 url(r'^admin/', admin.site.urls)的 admin

      django amdin是django提供的一个后台管理页面,改管理页面提供完善的html和css,使得你在通过Model创建完数据库表之后,就可以对数据进行增删改查

    3.2.1创建一个用户

     3.2.2向admin中增加一栏 UserInfo

     3.2.3效果

    4.函数(模版和数据渲染)

    4.1模版

    4.1.1模版的执行

    模版的创建过程,对于模版,其实就是读取模版(其中嵌套着模版标签),然后将 Model 中获取的数据插入到模版中,最后将信息返回给用户。

    4.1.2模版语言

    •{{ item }}
    •{% for item in item_list %}  <a>{{ item }}</a>  {% endfor %}
      forloop.counter
      forloop.first
      forloop.last 
    •{% if ordered_warranty %}  {% else %} {% endif %}
    •母板:{% block title %}{% endblock %}
    子板:{% extends "base.html" %}
       {% block title %}{% endblock %}
    •帮助方法:
    {{ item.event_start|date:"Y-m-d H:i:s"}}
    {{ bio|truncatewords:"30" }}
    {{ my_list|first|upper }}
    {{ name|lower }}
    View Code

    4.2自定义simple_filter ,simple_tag  (模板自定义函数)

    a、在app中创建templatetags模块

    b、创建任意 .py 文件,如:xx.py

    from django import template
    
    register = template.Library()    #register  一词固定写法
    
    @register.filter
    def my_upper(value):
        return value.upper()
    
    
    @register.filter
    def my_u(value,arg):
        return value+arg
    
    
    @register.filter
    def my_bool(value):
        return False
    
    
    @register.simple_tag
    def my_lower(value,a1,a2,a3):
    
        return value + a1 + a2 + a3
    View Code

    c、在使用自定义simple_tag的html文件中导入之前创建的 xx.py 文件名

    {% load xx %}
    {# 导入此句 #}
    
    
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <h1>打印字典所有的key</h1>
    
        {{ name|my_upper }}
        {{ name|my_u:'666' }}
    
    
    
        <h2>filter</h2>
            {{ name|my_u:"666" }}
    
            {% if name|my_bool %}
                <h3>真</h3>
            {% else %}
                <h3>假</h3>
            {% endif %}
        <h2>tag</h2>
            {% my_lower "ALEX" "x" "SB" "V" %}
    
    
    
    </body>
    </html>
    View Code

    d、在settings中配置当前app,不然django无法找到自定义的simple_tag

    INSTALLED_APPS = (
    
        'django.contrib.admin',
    
        'django.contrib.auth',
    
        'django.contrib.contenttypes',
    
        'django.contrib.sessions',
    
        'django.contrib.messages',
    
        'django.contrib.staticfiles',
    
        'app01',
    
    )
    View Code

    4.3母版

    4.3.1layout.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title></title>
        <link rel="stylesheet" href="/static/plugins/bootstrap-3.3.7-dist/css/bootstrap.css" />
        <link rel="stylesheet" href="/static/plugins/font-awesome-4.7.0/css/font-awesome.css" />
        <link rel="stylesheet" href="/static/css/commons.css" />
        {% block css %}{% endblock %}
    </head>
    <body>
    
    
        <div class="pg-header">
            <div class="logo left">老男孩后台管理</div>
            <div class="avatar right" style="position: relative">
                <img style=" 40px;height: 40px;" src="/static/images/1.jpg">
                <div class="user-info">
                    <a>个人资料</a>
                    <a>注销</a>
                </div>
            </div>
            <div class="rmenus right">
                <a><i class="fa fa-commenting-o" aria-hidden="true"></i> 消息</a>
                <a><i class="fa fa-envelope-o" aria-hidden="true"></i> 邮件</a>
            </div>
        </div>
        <div class="pg-body">
            <div class="menus">
                <a> <i class="fa fa-futbol-o" aria-hidden="true"></i> 班级管理</a>
                <a>学生管</a>
                <a>老师管理</a>
            </div>
            <div class="content">
                <ol class="breadcrumb">
                  <li><a href="#">首页</a></li>
                  <li><a href="#">班级管理</a></li>
                  <li class="active">添加班级</li>
                </ol>
                {% block xx  %}{% endblock %}
    
            </div>
        </div>
        {% block js %}{% endblock %}
    
    
    
    
    </body>
    </html>
    View Code

    4.3.2index,html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    
        <ul>
            {% for row in posts.object_list %}
                <li>{{ row.name }}</li>
            {% endfor %}
        </ul>
    
        <div>
            {% if posts.has_previous %}
                <a href="/index.html?page={{ posts.previous_page_number }}">上一页</a>
            {% endif %}
    
    
            {% if posts.has_next %}
                <a href="/index.html?page={{ posts.next_page_number }}">下一页</a>
            {% endif %}
        </div>
    
    
    
    </body>
    </html>
    View Code

    #笔记内容

    layout.html
                {% block x1 %}{%endblock%}
                <h1>ff</h1>
                {% block x2 %}{%endblock%}
                <h1>2</h1>...
                {% block x3 %}{%endblock%}
            index.html
                {%extends 'layout'%}
                
                {% block x1 %}dfssssssdfsd{%endblock%}
                
                {% block x2 %}dfsdfsd{%endblock%}
                
                {% block x3 %}fff{%endblock%}
    View Code

     4.4include

    a.pub.html(只有一个 div)

    <div>
        <h3>特别漂亮的组件</h3>
        <div>
            <div class="title">标题:</div>
            <div class="content">内容:</div>
    
        </div>
    </div>
    View Code

    b.在另一个.html中,引入使用

    % load xx %}
    {# 导入此句 #}
    
    
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    
    
        {% include 'pub.html' %}
        {% include 'pub.html' %}
        {% include 'pub.html' %}
         {% include 'pub.html' %}
        
    
    
    
    
    {#    <h1>打印字典所有的key</h1>#}
    {##}
    {#    {{ name|my_upper }}#}
    {#    {{ name|my_u:'666' }}#}
    {##}
    {##}
    {##}
    {#    <h2>filter</h2>#}
    {#        {{ name|my_u:"666" }}#}
    {##}
    {#        {% if name|my_bool %}#}
    {#            <h3>真</h3>#}
    {#        {% else %}#}
    {#            <h3>假</h3>#}
    {#        {% endif %}#}
    {#    <h2>tag</h2>#}
    {#        {% my_lower "ALEX" "x" "SB" "V" %}#}
    
    
    
    </body>
    </html>
    View Code

    #笔记内容

    1. 模板
            - 基本使用
            - 母版
                - 页面继承
            - include
                - 导入小组件
                    pub.html
                        <div>
                            <h3>特别漂亮的组件</h3>
                            <div class="title">标题:{{ name }}</div>
                            <div class="content">内容:{{ name }}</div>
                        </div>
                    test.html
                        <!DOCTYPE html>
                        <html lang="en">
                        <head>
                            <meta charset="UTF-8">
                            <title></title>
                        </head>
                        <body>
                            {% include 'pub.html' %}
                            {% include 'pub.html' %}
                            {% include 'pub.html' %}
                        </body>
                        </html>
            - 函数-> 自动执行
            - 模板自定义函数:
                - simple_filter
                    - 最多两个参数,方式: {{第一个参数|函数名称:"第二个参数"}}
                    - 可以做条件判断
                - simple_tag
                    - 无限制: {% 函数名 参数 参数%}
    View Code

    4.8 ORM

    4.8.1 Http请求:

        url -----> 视图(模版+数据)

    4.8.2 步骤:

    1.在Mysql,创建数据库

    2.

     3.

    4.8.3 ORM操作表:
                创建表
                修改表
                删除表
            操作数据行:
                增删改查
               

    4.8.4 ORM利用pymysql第三方工具连接数据库
            默认:
                SQLlite
            MySQL:
                mysql -> MySQLDB(修改django默认连接mySQL方式)

    4.8.5 数据类型

    # 数据获取多个数据时
                # 1. [obj,obj,obj,]
                # models.UserInfo.objects.all()
                # models.UserInfo.objects.filter(id__gt=1)
                # result = models.UserInfo.objects.all()
                # for item in result:
                #     print(item.name,item.ut.title)
    
                # 2. [{id:1,name:fd},{id:1,name:fd},{id:1,name:fd},]
                # models.UserInfo.objects.all().values('id','name')
                # models.UserInfo.objects.filter(id__gt=1).values('id','name')
                # 无法跨表
                # result = models.UserInfo.objects.all().values('id','name')
                # for item in result:
                #     print(item['id'],item['name'])
                # 夸表  __
                # result = models.UserInfo.objects.all().values('id','name',"ut__title")
                # for item in result:
                #     print(item['id'],item['name'],item['ut__title'])
    
    
                # 3. [(1,df),(2,'df')]
                # models.UserInfo.objects.all().values_list('id','name')
                # models.UserInfo.objects.filter(id__gt=1).values_list('id','name')
                # 无法跨表
                # result = models.UserInfo.objects.all().values_list('id','name')
                # for item in result:
                #     print(item[0],item[1])0
                # 夸表  __
                # result = models.UserInfo.objects.all().values_list('id','name',"ut__title")
                # for item in result:
                #     print(item[0],item[1],item[2])
    View Code

    4.8.6 操作

    # 1.增删改查
                # 2. 一般:
                    # models.UserInfo.objects.filter(id__gt=1)
                    # models.UserInfo.objects.filter(id__lt=1)
                    # models.UserInfo.objects.filter(id__lte=1)
                    # models.UserInfo.objects.filter(id__gte=1)
                    # models.UserInfo.objects.filter(id__in=[1,2,3])
                    # models.UserInfo.objects.filter(id__range=[1,2])
                    # models.UserInfo.objects.filter(name__startswith='xxxx')
                    # models.UserInfo.objects.filter(name__contains='xxxx')
                    # models.UserInfo.objects.exclude(id=1)
                # 3. 排序
                    user_list = models.UserInfo.objects.all().order_by('-id','name')
                
                # 4. 分组
                    from django.db.models import Count,Sum,Max,Min
                    # v =models.UserInfo.objects.values('ut_id').annotate(xxxx=Count('id'))
                    # print(v.query)
                    # v =models.UserInfo.objects.values('ut_id').annotate(xxxx=Count('id')).filter(xxxx__gt=2)
                    # print(v.query)
                    # v =models.UserInfo.objects.filter(id__gt=2).values('ut_id').annotate(xxxx=Count('id')).filter(xxxx__gt=2)
                    # print(v.query)
                    
                
                
                # 5. F,更新时用于获取原来的值
                    # from django.db.models import F,Q
                    # models.UserInfo.objects.all().update(age=F("age")+1)
                
                # 6. Q,用于构造复杂查询条件
                    # 应用一:
                            # models.UserInfo.objects.filter(Q(id__gt=1))
                            # models.UserInfo.objects.filter(Q(id=8) | Q(id=2))
                            # models.UserInfo.objects.filter(Q(id=8) & Q(id=2))
                    # 应用二:
                            # q1 = Q()
                            # q1.connector = 'OR'
                            # q1.children.append(('id__gt', 1))
                            # q1.children.append(('id', 10))
                            # q1.children.append(('id', 9))
                            #
                            #
                            # q2 = Q()
                            # q2.connector = 'OR'
                            # q2.children.append(('c1', 1))
                            # q2.children.append(('c1', 10))
                            # q2.children.append(('c1', 9))
                            #
                            # q3 = Q()
                            # q3.connector = 'AND'
                            # q3.children.append(('id', 1))
                            # q3.children.append(('id', 2))
                            # q2.add(q3,'OR')
                            #
                            # con = Q()
                            # con.add(q1, 'AND')
                            # con.add(q2, 'AND')
                            
                            # models.UserInfo.objects.filter(con)
                
                # 7. extra, 额外查询条件以及相关表,排序
                
                    models.UserInfo.objects.filter(id__gt=1)
                    models.UserInfo.objects.all() 
                    # id name age ut_id
                
                
                    models.UserInfo.objects.extra(self, select=None, where=None, params=None, tables=None, order_by=None, select_params=None)
                    # a. 映射
                        # select 
                        # select_params=None
                        # select 此处 from 表
                    
                    # b. 条件
                        # where=None
                        # params=None,
                        # select * from 表 where 此处
                    
                    # c. 表
                        # tables
                        # select * from 表,此处
                        
                    # c. 排序
                        # order_by=None
                        # select * from 表 order by 此处
                    
                    
                    models.UserInfo.objects.extra(
                        select={'newid':'select count(1) from app01_usertype where id>%s'},
                        select_params=[1,],
                        where = ['age>%s'],
                        params=[18,],
                        order_by=['-age'],
                        tables=['app01_usertype']
                    )
                    """
                    select 
                        app01_userinfo.id,
                        (select count(1) from app01_usertype where id>1) as newid
                    from app01_userinfo,app01_usertype
                    where 
                        app01_userinfo.age > 18
                    order by 
                        app01_userinfo.age desc
                    """
                    
                    result = models.UserInfo.objects.filter(id__gt=1).extra(
                        where=['app01_userinfo.id < %s'],
                        params=[100,],
                        tables=['app01_usertype'],
                        order_by=['-app01_userinfo.id'],
                        select={'uid':1,'sw':"select count(1) from app01_userinfo"}
                    )
                    print(result.query)
                    # SELECT (1) AS "uid", (select count(1) from app01_userinfo) AS "sw", "app01_userinfo"."id", "app01_userinfo"."name", "app01_userinfo"."age", "app01_userinfo"."ut_id" FROM "app01_userinfo" , "app01_usertype" WHERE ("app01_userinfo"."id" > 1 AND (app01_userinfo.id < 100)) ORDER BY ("app01_userinfo".id) DESC
                
                # 8. 原生SQL语句
                
                    from django.db import connection, connections
                    
                    cursor = connection.cursor() # connection=default数据
                    cursor = connections['db2'].cursor()
                    
                    cursor.execute("""SELECT * from auth_user where id = %s""", [1])
                    
                    row = cursor.fetchone()
                    row = cursor.fetchall()
                    
                    
                    - extra
                    - 原生SQL语句
                    - raw
                        result = models.UserInfo.objects.raw('select * from userinfo')
                        [obj(UserInfo),obj,]
                        result = models.UserInfo.objects.raw('select id,1 as name,2 as age,4 as ut_id from usertype')
                        [obj(UserInfo),obj,]
                        
                        v1 = models.UserInfo.objects.raw('SELECT id,title FROM app01_usertype',translations=name_map)
    
    
    
    # 9. 简单的操作
                    http://www.cnblogs.com/wupeiqi/articles/6216618.html
                        
    View Code

    补充内容:

    1.简单登录

    1.1 view.py

    def login(request):
        if request.method == 'GET':
            return render(request,'login.html')
        else:
            u = request.POST.get('user')
            p = request.POST.get('pwd')
    
            if u=='alex' and p=='123':
                request.session['username']='alex'
                request.session['email'] = 'alex3714@qq.com'
                return redirect('/index/')
            else:
                return render(request,'login.html',{'msg':'用户名或密码错误'})
    
    def index(request):
       
    
    
        return HttpResponse('登录成功')
    View Code

    1.2 login.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <form method="POST" action="/login/">
            {% csrf_token %}
            <input type="text" name="user" />
            <input type="text" name="pwd" />
            <input type="submit"value="提交" />{{ msg }}
        </form>
    </body>
    </html>
    View Code

    2.登录

    2.1url.py

    rom django.conf.urls import url
    from django.contrib import admin
    from app01.views import account
    from app01.views import love
    
    
    urlpatterns = [
        url(r'^admin/', admin.site.urls),
        url(r'^login.html$', account.login),
        url(r'^logout.html$', account.logout),
    
    
        url(r'^index.html$', love.index),
        url(r'^others.html$', love.others),
    
    
    
    
    ]
    View Code

    2.2

    account.py

    from django.shortcuts import render,HttpResponse,redirect
    from app01 import models
    def login(request):
    
        if request.method == 'GET':
            return render(request,'login.html')
        else:
            user = request.POST.get('username')
            pwd = request.POST.get('password')
            gender = request.POST.get('gender')
            rmb = request.POST.get('rmb')
    
            # 性别判断
            if gender == "1":
                obj = models.Boy.objects.filter(username=user,password=pwd).first()
            else:
                obj = models.Girl.objects.filter(username=user,password=pwd).first()
            if not obj:
                # 未登录
                return render(request,'login.html',{'msg': '用户名或密码错误'})
            else:
                # request.session['user_id'] = obj.id
                # request.session['gender'] = gender
                # request.session['username'] = user
    
    
                request.session['user_info'] = {'user_id':obj.id,'gender':gender,'username':user,'nickname':obj.nickname}
                return redirect('/index.html')
    
    def logout(request):
        if request.session.get('user_info'):
            request.session.clear()
            # request.session.delete(request.session.session_key)
        return redirect('/login.html')
    View Code

    love.py

    from django.shortcuts import render,HttpResponse,redirect
    from app01 import models
    
    def index(request):
        if not request.session.get('user_info'):
            return redirect('/login.html')
        else:
    
            #男:女生列表
            #女:男生列表
            gender = request.session.get('user_info').get('gender')
            if gender == '1':
                user_list = models.Girl.objects.all()
            else:
                user_list = models.Boy.objects.all()
            return render(request,'index.html',{'user_list':user_list})
    
    
    def others(request):
        """
        获取与当前用户有关系的异性
        :param request:
        :return:
        """
    
        current_user_id = request.session.get('user_info').get('user_id')
        gender =request.session.get('user_info').get('gender')
    
        if gender == '1':
            user_list = models.B2G.objects.filter(b_id=current_user_id).values('g__nickname')
        else:
            user_list =  models.B2G.objects.filter(g_id=current_user_id).values('b__nickname')
    
        return render(request,'others.html',{'user_list':user_list})
    View Code

    index.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        {% include 'user_header.html' %}
    
        <h3>异性列表</h3>
        <a href="/others.html">查看和我有关系的异性</a>
        <ul>
            {% for row in user_list %}
                <li>{{ row.nickname }}</li>
            {% endfor %}
        </ul>
    
    
    
    </body>
    </html>
    View Code

    login.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <form method="POST" action="/login.html">
            {% csrf_token %}
            <p>用户:<input type="text" name="username" /></p>
            <p>密码:<input type="password" name="password" /></p>
            <p>
                性别:
                    男<input type="radio" name="gender" value="1" /><input type="radio" name="gender" value="2" />
            </p>
            <p>
                <input type="checkbox" name="rmb" value="11"  /> 一个月免登录
            </p>
            <input type="submit" value="提交" />{{ msg }}
        </form>
    
    
    
    </body>
    </html>
    View Code

    models.py

    from django.db import models
    
    # Create your models here.
    
    
    class Boy(models.Model):
    
        nickname = models.CharField(max_length=32)
        username = models.CharField(max_length=32)
        password = models.CharField(max_length=64)
    
    
    class Girl(models.Model):
        nickname = models.CharField(max_length=32)
        username = models.CharField(max_length=32)
        password = models.CharField(max_length=64)
    
    
    class B2G(models.Model):
    
        b = models.ForeignKey(to='Boy',to_field='id')
        g = models.ForeignKey(to='Girl',to_field='id')
    View Code
    t = {'k':'世界 你好'}
    import json
    
    ret = json.dumps(t)
    
    print(ret)    #{"k": "u4e16u754c u4f60u597d"}
    t = {'k':'世界 你好'}
    import json
    
    ret = json.dumps(t,ensure_ascii=False)
    
    
    print(ret)    #{"k": "世界 你好"}
  • 相关阅读:
    Java 工程名上有个红色叹号
    TestNG 入门教程
    字典序问题
    统计数字问题
    sniffer 简介
    【转】IE浏览器快捷键大全
    批处理 延时不完全总结【转】
    批处理(Batch)---批处理脚本。
    windows系统命令行
    计算机网络
  • 原文地址:https://www.cnblogs.com/zhaochangbo/p/7105005.html
Copyright © 2011-2022 走看看