• Django 内容回顾


    • 模板

      • 变量 {{ }}

      • 标签 {% %}

        • if elif else

        • for empty forloop()

        • with...as

        • csrf_token

      • 过滤器

        • default

        • length

        • add

        • data Y-m-d H:i:s 也可以在settings配置全局 DATATIME_FORMAT = ‘Y-m-d H:i:s’ USE_10N=False

        • filesizeformat

        • slice

        • safe 跨站脚本攻击

        • truncatechars 截断

      • 组件 一小段代码段

        • include html文件

      • 母版和继承

        • 母:block 名字 占位置 css/js/content

        • 子:entends base.html第一行 block 名字 进行生效

      • 静态文件相关

        • {% load static %} {% static ‘路径’ %}

        • {% load static %} {% get_static_prefix %}路径/

          • 静态文件相关(动态拿取STATIC_URL配置的名字)
                  -
                      {% load static %}
                      <img src="{% static "images/hi.jpg" %}" alt="Hi!" />
                       
                      引用JS文件时使用:
                      {% load static %}
                      <script src="{% static "mytest.js" %}"></script>
                       
                      某个文件多处被用到可以存为一个变量
                      {% load static %}
                      {% static "images/hi.jpg" as myphoto %}
                      <img src="{{ myphoto }}"></img>

                  - get_static_prefix
                      {% load static %}
                      <img src="{% get_static_prefix %}images/hi.jpg" alt="Hi!" />
                       
                      或者
                      {% load static %}
                      {% get_static_prefix as STATIC_PREFIX %}

                      <img src="{{ STATIC_PREFIX }}images/hi.jpg" alt="Hi!" />
                      <img src="{{ STATIC_PREFIX }}images/hi2.jpg" alt="Hello!" />
      • 自定义 filter|simple_tag |inclusion_tag

        • filter 变量

          • 编写自定义filter

                   
                          from django import template
                          register = template.Library()


                          @register.filter
                          def fill(value, arg):
                              return value.replace(" ", arg)


                          @register.filter(name="addSB")
                          def add_sb(value):
                              return "{} SB".format(value)
                       
                      - 使用自定义filter

                          {# 先导入我们自定义filter那个文件 #}
                          {% load app01_filters %}

                          {# 使用我们自定义的filter #}
                          {{ somevariable|fill:"__" }}
                          {{ d.name|addSB }}
        • simple_tag

          • 自定义simple_tag
                  和自定义filter类似,只不过接收更灵活的参数。

                  定义注册simple_tag
                  @register.simple_tag

                  @register.simple_tag(name="plus")
                  def plus(a, b, c):
                      return "{} + {} + {}".format(a, b, c)

                  使用自定义simple_tag
                  {% load app01_demo %}

                  {# simple tag #}
                  {% plus "1" "2" "abc" %}
        • inclusion_tag

          • inclusion_tag
                  - 多用于返回html代码片段

                  - 步骤
                      - 在app下创建templatetags的python包
                      - 在包下写py文件 mytags
                      - 编辑文件
                          - from django import template
                          - register = template.Library()

                      - 定义函数
                          - 可接受参数
                          - 返回一个字典
                      - 函数加装饰器
                          - @register.inclusion_tag('result.html')

                  示例:

                      templatetags/my_inclusion.py

                       
                          from django import template

                          register = template.Library()


                          @register.inclusion_tag('result.html')
                          def show_results(n):
                              n = 1 if n < 1 else int(n)
                              data = ["第{}项".format(i) for i in range(1, n+1)]
                              return {"data": data}
                   
                      templates/result.html

                          <ul>
                            {% for choice in data %}
                              <li>{{ choice }}</li>
                            {% endfor %}
                          </ul>
                       
                      templates/index.html
                           
                          <!DOCTYPE html>
                          <html lang="en">
                          <head>
                            <meta charset="UTF-8">
                            <meta http-equiv="x-ua-compatible" content="IE=edge">
                            <meta name="viewport" content="width=device-width, initial-scale=1">
                            <title>inclusion_tag test</title>
                          </head>
                          <body>

                          {% load my_inclusion %}

                          {% show_results 10 %}
                          </body>
                          </html>
    • 视图

      • FBV和CBV

      • CBV流程

        • as_view()->view方法->dispatch

      • 加装饰器的方法

        • csrf相关的两个装饰器,只能加在dispatch上面

        • FBV 普通加法 @wrapper def test()

        • CBV from django.utils.decorators import method_decorator

        1. 加在方法上 @method_decorator(timer) def get(self, request):

        2. 加在dispatch上 @method_decorator(timer) def dispatch(self, request, *args, **kwargs)

        3. 加在类上 @method_decorator(timer,name='post') @method_decorator(timer,name='get') class AddPress(View):

      • request

        • 属性

          • method

          • GET url数据

          • POST 数据

          • FILES 文件

          • path_info 获取路径 不包括参数 ip和端口

          • body 真正的数据存放的位置(bytes类型的request),POST的数据就是在body中提取出来的

        • 方法

          • get_full_path() 获取路径和参数 不包括ip和端口

          • get_host() ip 端口

          • is_ajax()

      • response

        • 三件套

        • ajax不能redirect对象。返给前端自己跳转=======HttpResponse。JsonResponse

    • 路由

      • urlpatterns=[]

      • 正则表达式 2.0 re_path = 1.0 url

      • 分组和命名分组

        • 分组:加括号,括号内容按位置参数传给视图

        • 命名分组(?<name> ) 关键字参数

        • 传的都是字符串

      • 参数

        • {}字典形式传给视图(可以看成默认参数)

      • include 路由分发

        • namespace

      • URL命名和反向解析

        • reverse

        • 灵活

          • url起名字

            • 视图:reverse(’名字‘)

            • {% url '名字' %}

          • 传参数

            • 视图:reverse(''名字'',args=(), kwargs=())

            • {% url '名字' 参数1' ''year= '2018' %}

      • namespace

        • Include(url,namespace='namespace名字')

          • url起名字

            • 视图:reverse(’namespace名字:名字‘)

            • {% url 'namespace名字:名字'%}

          • 传参数

            • 视图:reverse(''namespace名字:名字'',args=(), kwargs=())

            • {%url 'namespace名字:名字' '参数1' ''year= '2018' %}

    • ORM

      • 对象关系映射

        • 字段类型

          • CharFiled

        • 参数

          • primary_key

          • choise·

      • 查询

        • 13种方法

          • all

          • filter

          • get

          • exclude

          • order_by

          • reverse

          • distinct

          • first

          • last

          • count

          • exist

          • values

          • values_list

        • 单表的双下方法

          • gt

          • lt

          • in

          • range

          • isnull

          • contents

          • icontents

          • starswith

          • endswith

          • __year

          • __day

          • __mounth

        • 外键的查询

          • 外键写在多的一方

          • 外键_id

          • 反向查询 表名_set 管理对象

        • 多对多的查询

          • ManyToMany

          • 会自动生成第三张表

          • 反向查询 表名_set 管理对象

            • 管理对象的方法

              • add(id)

              • remove(id)

              • set(列表)

              • clear()

          • update和save

            • update是指定的一个字段

            • save是所有

        • 高级操作

          • 聚合和分组

            • 聚合

              • aggregate

              • Max, Min, Avg, Sum,Count

            • 分组

              • annotate

          • F和Q

            • F

              • 字段之间的比较和操作

            • Q

              • 条件

                • |

                • &

                • ~

          • 事务

            • 同生共死

            • 把一些列的操作(步骤)当作一个事务

              全部的步骤都成功才成功

              经典例子:银行转账

               

              代码实现:

              import os

              if name == 'main': os.environ.setdefault("DJANGO_SETTINGS_MODULE", "BMS.settings") import django django.setup()

              import datetime
              from app01 import models

                try:
                    from django.db import transaction # 事务
                    with transaction.atomic(): # 里面是执行的所有步骤
                        new_publisher = models.Publisher.objects.create(name="火星出版社")
                        models.Book.objects.create(title="橘子物语", publish_date=datetime.date.today(), publisher_id=10) # 指定一个不存在的出版社id
                except Exception as e:
                    print(str(e))
    • cookie和session

      • cookie

        • 保存在浏览器的一组组键值对

        • 是浏览保存的,浏览器可以拒绝

        • 在Django中操作

          • 设置:HTTPResponse对象设置 res.set_cookie

            • 过期时间

            • 就还有一中加盐的cookie

          • 获取

            • request.COOKIES

            • 加盐有加盐的方法

          • 删除

            • request.clear_cookie()

      • session

        • cookie有限制不安全就用session

        • session是放在服务端的键值对

        • 设置

          • 字典的方式设置

          • setdefault

        • 获取

        • 删除

          • delate

          • flush

        • 设置session的超时时间

          • set_expiry()

        • 清除所有的过期session

          • clear_expired() 在Django_session表中删

        • 配置

          • 可以存在不同的地方 引擎

            • 在settings中配置

    • 中间件

      • 一个类

      • 在全局范围类处理请求和响应的钩子

      • 继承类MiddlewareMixin

      • 五中方法

    • ajax

      • 异步的局部刷新的数据库比较小

      • js的技术

      • 给服务器发请求交互的技术

      • 上传文件

        • FormData对象

        • 注意两个对象

          • processDate:false

          • contentType:false

        • csrf的保护机制

        • 流程

          • cookie中的值与process_request 和process_view 中的值作比较

        • 方式

          • {%csrf_tocken%}

          • 补充两个装饰器 from django.views.decorators.csrf import csrf_exempt, csrf_protect csrf_exempt 给单个视图排除校验 csrf_protect 给单个视图必须校验

            • process_request 从请求的cookie中获取csrftoken的值 ——》csrf_token ——》request.META['CSRF_COOKIE'] process_view:

              1如果视图函数加上了csrf_exempt的装饰器 不做校验

              2如果请求方式是'GET', 'HEAD', 'OPTIONS', 'TRACE' 也不做校验

              3其他的请求方式做校验 request.META.get('CSRF_COOKIE') —— 》 csrf_token

     

           request_csrf_token = "" 从request.POST中获取csrfmiddlewaretoken对应的值

        request_csrf_token = request.POST.get('csrfmiddlewaretoken', '')

        从请求头中获取X-csrftoken 的值

        request_csrf_token = request.META.get(settings.CSRF_HEADER_NAME, '')

        request_csrf_token 和 csrf_token 做对比  
        如果校验成功 正常走
        如果校验不成功 拒绝

    - 某一个请求(两种方式)

      - 数据发送
      - 请求头发送 X-CSRFToken

    - 全局

      - 自己导入
      - 还需要加一个装饰器
    • Form

      • Django提供的Form组件

      • 定义一个类 from django import forms

      • 继承 forms.Form

      • 写字段

        • 参数

          • choises

          • validate

            • 正则

            • 函数

              • 不符合抛出异常

              • 判断条件没有返回值

          • widget

            • 插件

            • attrs 写样式

          • 钩子函数

            • 局部钩子

              • clean_字段名(self):

            • 全局钩子

              • clean(self):

    • auth

      • 是一个app Django写好的

      • 有一个中间件

      • 与session配合使用

      • 方法:

        • authenticate

        • login

        • logout

        • 跳转其他页面

          • from django.contrib.auth.decorators import login_required

          • 装饰器 login_require

          • 在settings中设置条转路径

        • 登录状态

          • is_authenticated

        • 密码

          • check_password

          • set_password + save

        • 创建用户

          • from django.contrib.auth.models import User 密码是明文的 User.objects.create(username=username,password=password) 密码是密文的 普通用户 User.objects.create_user(form_obj.cleaned_data) 创建超级用户 User.objects.create_superuser(email='',**form_obj.cleaned_data)

          • Is_staff 是否管理员

          • is_active 是否允许 用户登录

        • 扩展表

          • 继承 from django.contrib.auth.models import AbstractUser

          • 在settings中配置

            • AUTH_USER_MODEL = ‘app中对应表名’ # ‘app.表名(类名)’

            •  Djan

  • 相关阅读:
    2015 12 04课堂随便
    java 循环制作三角形
    2015 12 3课堂随笔
    张王李相亲应用if else
    2015 12 01 课堂笔记。 运算符的使用
    Java图形化界面设计——布局管理器之null布局(空布局)
    jQuery
    jQuery
    jQuery
    jQuery
  • 原文地址:https://www.cnblogs.com/xiao-xue-di/p/9833193.html
Copyright © 2020-2023  润新知