django- view layer and template layer

1. view layer
  white will be three axes
 1.HttpResponse
  return the HttpResponse ( 'string')
 2.render
  return the render (Request, 'the HTML page', { 'name': name})
 3.redirect
  return the redirect ( 'Select to jump to the page / ')
  summary: view function must have a return value and return value data types must HttpResponse object.

2.JsonResponse
 before and after the end of the separation; how the front and back end data exchange carried out?
  Usually json string (dictionary) data before and after the end of the use case of interaction
 (back-end need only write the appropriate url front-end interface to access this interface you only need to return a large dictionary to + development documents, used to tell this interface can be the front end of which you engineer data return)

 front and rear ends of the sequence of what method anti sequences
  python rear JS
  json.dumps the JSON.stringify
  json.loads the JSON.parse

  user_dic = { 'name': 'jan Hello', 'password': '123'}

  How to make json not automatically help you to Chinese transcoding
  json_str = json.dumps (user_dic, ensure_ascii = False), where (ensure_ascii = False) default is True, changed to False, you can show the Chinese! !

   (1).return HttpResponse(json_str)

   (2).return JsonResponse(user_dic,json_dumps_params={'ensure_ascii':False})

  = L [1,2,3,4,5,6,7,]
  jsonResponse; default serialization dictionary if you want to use the sequence of the other data types (JSON serialization module can) you need to add a parameter safe
  return jsonResponse (l, safe = False)

3.FBV and the CBV
  the FBV: based on the view function
  CBV: based on the view class
  from django.views import View

  MyLogin class (View):
    DEF get (Self, Request):
      Print ( 'I am MyLogin inside the get method')
    return the render (Request, 'login.html')

    post DEF (Self, Request):
      Print ( 'I am MyLogin inside the post method')
    return HttpResponse ( 'post')

  Routing writing a little different with the CBV

  >>> view FBV wording routing function memory address
    URL (R & lt 'index ^ /', views.index),
  the CBV written
    url (r '^ login /' , views.MyLogin.as_view ())

Access properties and methods:

The method is the function (function name in parentheses implementation of the highest priority) project will start automatically performs a method as_view

  参考截图
  @classonlymethod
  def as_view(cls, **initkwargs):
    def view(request, *args, **kwargs):   # 闭包函数
      self = cls(**initkwargs)   # cls是我们自己写的类 MyLogin self是我们自己定义的类的对象
       # 在看源码的时候 你一定要把握住一个顺序 对象在查找属性和方法的时候
       # 先从对象自身找 再去产生对象的类中找 再去类的父类中找
      return self.dispatch(request, *args, **kwargs)
    return view


  def dispatch(self, request, *args, **kwargs):
        # 判断当前请求方式在不在默认的八个方法内
        # 1.先以GET请求为例  
    if request.method.lower() in self.http_method_names:
     # 利用反射去我们自己定义类的对象中查找get属性或者是方法 getattr(obj,'get')
     # handler = get方法
      handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
    else:
      handler = self.http_method_not_allowed
    return handler(request, *args, **kwargs) # 调用get方法

 

  给CBV加装饰器 推荐你使用内置模块
  from django.utils.decorators import method_decorator

  2.可以指定给谁装
  @method_decorator(outter,name='post')
  @method_decorator(outter,name='dispatch')
  class MyLogin(View):
    @method_decorator(outter)
    def dispatch(self, request, *args, **kwargs): # 如果你想在视图函数执行之前 做一些操作 你可以在你的CBV中定义dispatch方法来拦截

      return super().dispatch(request,*args,**kwargs)
  #@outter # 1.直接写
  #@method_decorator(outter) # 1.推荐写法
  def get(self,request):
    print('我是MyLogin里面的get方法')
    return render(request,'login.html')
    #@outter 2.直接写
  def post(self,request):
    print('我是MyLogin里面的post方法')
    time.sleep(1)
    return HttpResponse('post')

4.模板层

 (1).模板语法
  只有两种书写格式
  {{}} 变量相关
  {%%} 逻辑相关

 (2).模板传值
  python基本数据类型全部支持传值

 (3).<p>传函数名:{{ index1 }}</p>
  给HTML页面传递函数名的时候 模板语法会自动加括号调用该函数 并且将函数的返回值当做展示依据
  模板语法不支持函数传参 也就意味着 你传给html页面的只能是不需要传参调用的函数

 (4).<p>传类名:{{ MyClass }}</p>
  自动加括号实例化产生对象

  <p>传对象:{{ obj }}</p>
  <p>{{ obj.get_self }}</p>
总结:只要是能够加括号调用的 传递到html页面上都会自动加括号调用

 (5).过滤器 语法结构: " | "
  模板语法也给你提供了一些内置的方法 帮你快速的处理数据,最多只能有两个参数
  <p>模板语法之过滤器 会自动将|左边的数据当前过滤器的第一个参数传入 :右边的当做第二个参数</p>

  {#<p>统计长度(如果无法统计默认返回0):{{ s|length }}</p>#}

  {#<p>加法运算(内部异常捕获 支持数字相加 字符串拼接 都不符合返回空):{{ n|add:f }}</p>#}

  {#<p>切片操作 顾头不顾尾 也支持步长:{{ l|slice:'0:5:2' }}</p>#}

  {#<p>判断是否有值(有值展示值本身 没值展示默认值):{{ is_value|default:'is_value变量名指向的值为空' }} </p>#}
  {#<p>自动转成文件大小格式:{{ file_size|filesizeformat }}</p>#}

  {#<p>截取文本内容(字符) 截取五个字符 三个点也算:{{ s|truncatechars:8 }}</p>#}

  {#<p>截取文本内容(按照空格计算) 截取五个单词 三个点不算 :{{ s1|truncatewords:5 }}</p>#}

  {#<p>默认情况下 是不会自动帮你转换成前端html标签 防止恶意攻击</p>#}

  {#<p>展示带有标签的文本:{{ sss|safe }}</p>#}

  {#<p>展示带有标签的文本:{{ sss1|safe }}</p>#}

  前后端取消转义
    前端: sss|safe
    后端:from django.utils.safestring import mark_safe
      sss2 = "<h2>我的h2标签</h2>"
      res = mark_safe(sss2) 


 (6).标签 逻辑相关
  if 判断        for循环
  for if联合使用
  {% for foo in l %}
    {% if forloop.first %}
      <p>第一次</p>
    {% elif forloop.last %}
      <p>最后一次</p>
    {% else %}
      <p>{{ foo }}</p>
    {% endif %}
  {% empty %}
  <p>当for循环的对象是空的时候会走</p>
  {% endfor %}

  <p>模板语法的取值 只有一种方式 统一采用句点符 (.)</p>
  <p>{{ comp_dic.hobby.2.2.age }}</p>


 (7).自定义过滤器和标签
  django支持用户自定义
  必须要先有三部准备:
   1.在应用名下新建一个名字必须叫templatetags的文件夹
   2.在该文件夹内 新建一个任意名称的py文件
   3.在该py文件中 必须先写下面两句代码
  from django.template import Library
  register = Library()
  之后就可以利用register来自定义过滤器和标签

  使用自定义的过滤器
    需要先在html页面上 加载
    自定义过滤器 跟默认的过滤器一样 最多只能接受两个参数
    @register.filter(name='baby')
    def index(a,b):
      return a + b

    自定义标签 可以接受任意多个参数
    @register.simple_tag(name='mytag')
    def mytag(a,b,c,d):
      return '%s?%s?%s?%s'%(a,b,c,d)

  自定义inclusion_tag

   是一个函数 能够接受外界传入的参数 然后传递给一个html页面,页面上获取数据 渲染 完成之后,将渲染好的页面 放到调用inclusion_tag的地方.

  自定义inclusion_tag
  @register.inclusion_tag('mytag.html',name='xxx')
  def index666(n):
    l = []
    for i in range(n):
    l.append('第%s项'%i)
    return locals() # 将l直接传递给mytag.html页面

  {#<p>自定义过滤器的使用</p>#}
  {#{% load index%}#}
  {#{{ 1|baby:1 }}#}
  {#{{ 1|baby:100 }}#}

  {#<p>自定义标签的使用 可以接受多个参数 参数与参数之间必须空格隔开</p>#}
  {#{% load mytag %}#}
  {#{% mytag 'a' 'b' 'c' 'd' %}#}
  {#{% load mytag %}#}
  {##}
  {#<p>自定义的过滤器可以在逻辑语句使用 而自定义的标签不可以</p>#}
  {#{% if mytag '1' '2' '3' '4' %}#}
    {# <p>有值</p>#}
    {# {% else %}#}
    {# <p>无值</p>#}
  {#{% endif %}#}

  定义inclusion_tag的使用 当你需要使用一些页面组件的时候 并且该页面组件需要参数才能够正常渲染 你可以考虑使用inclusion_tag  

 (8)模板的继承
  你需要事先在你想要使用的页面上 划定区域 之后在继承的时候 你就可以使用你划定的区域;
  也就意味着 如果你不划定任何区域 那么你将无法修改页面内容.

  继承之后 就可以通过名字找到对应的区域进行修改
  {% extends 'home.html' %}

  {% block content %}
    修改模板中content区域内容
  {% endblock %}

  模板上的block区域越多 页面的扩展性越强;建议你一个模板页面至少有三块区域
  css区域
  html代码区域 可以设置多个block
  js区域
  有了这三块区域 就能够实现每一个页面都有自己独立的css和js代码
  {% extends 'home.html' %}

  {% block css %}
    <style>
      p {
        color: green;
       }
    </style>
  {% endblock %}

  {% block content %}
    <p>login页面</p>
  {% endblock %}

  {% block js %}
    <script>
      alert('login')
    </script>
  {% endblock %}
  你还可以在子页面上继续沿用父页面的内容
  {{ block.super }}

 (9).模板的继承
  1.先在你想要继承的页面上通过block划定你将来可能要改的区域
  2.在子页面上先继承extends
  3.利用block自动提取 选择你想要修改的内容区域

 (10).模板的导入
  将html页面当做模块的直接导入使用
  {% include 'bform.html' %}
  {#<form action="">#}
  {# {{ form }}#}
  {#</form>#}
  include导入的相当于下面注释的form表单的内容

 

 

Guess you like

Origin www.cnblogs.com/mqhpy/p/11938513.html