An internal principle day54_9_18 view layer (fbv and cbv) and the template layer

One. render internal principle.

  In render often require returns three parameters, request, templates and a few pairs.

  Key-value pairs stored value is the need for template rendering.

  If the manual can achieve the following:

from django.template import Template,Context
def index(request):
    temp = Template('<h1>{{ user }}</h1>')
    con = Context({"user":{"name":'jason',"password":'123'}})
    res = temp.render(con)
    print(res)
    return HttpResponse(res)

   First get the template, and then render the template rendering, and finally return to the use of a string.

two. FBV and CBV

  FBV(function base view)

  CBV(class base view)

  Is a view of a function based on written, it is a view of a class based on the preparation.

  For value-based writing function it is to run its return value, which is generated by three rendering template functions.

  Based on the type written to run the function of a built-view function class functions generated essentially a closure function.

  Write functions:

from django.views import View
class MyLogin(View):
    def get(self,request):
            print("from MyLogin get方法")
        return render(request,'login.html')
    def post(self,request):
        return HttpResponse("from MyLogin post方法")        

  Write url:

url(r'^login/',views.MyLogin.as_view())

  You can see where you need to call mylogin running their preparation classes as_view function. However, this function is a function of the inherited VIew.

  as_view

  as_view binding is a function of the class method. In addition to the normal exception handling, which has an internal closure function, that is to say the result after calling this function is the return value of this function of view.

  Url When the matching is successful, calls the view function, returns inside view is to use a dispatch method (a method inherited from the parent class View) custom function generated object.

  Also said that the final value is the value returned by dispatch generated. That is rendering the page. dispatch will first determine whether your request is one of the eight basic requests belong. If it is on by itself, and the target character string generated class definitions, getattr obtain a corresponding function, and finally returned template rendered by this function to get running.

Eight kinds of requests: 
http_method_names =
[ ' GET ' , ' POST ' , ' PUT ' , ' Patch ' , ' Delete ' , ' head ' , ' Options ' , ' the trace ' ]

three. Django settings in the source code.

  For django of settings are available to our configuration file, in addition to capital variables, other variables have no effect, it will go through its unique internal processing.

  In fact, there is a frame in django global profile, the user's settings are exposed to a small part, which call as follows:

from django.conf import settings

  First introduced os.environ. This is equivalent to a global dictionary, any dictionary-value settings can support. Secondly dir method, dir all the variables may be the name of a module removed.

  When django starts, it will run directly manage.py file, which will first be exposed to the user settings path to the variable name: DJANGO_SETTINGS_MODULE is key, adding the global dictionary.

  In the method of internal settings embodiment is a single mode, settings whenever the call, returns an object LazySettings ()

  In LazySettings () internal acquired first string exposure settings to the user from the global dictionary, which was passed to the method to configure settings.

  dir settings method first loop method for obtaining all configuration and global settings, if it is added to the object of his capital generated, that is, when the calling module.

  Followed calling user-configured settings, calling module string. Also use a for loop. If the original cover is provided on its present value, it is not new.

  That will give priority to using the user's settings.

four. Pass the template layer of value.

  When we use the function by value to the view template, generally using a dictionary approach.

DEF index (Request):
     return the render (requset, ' HTML ' , { ' name': 'data'})

  Hou However, when a plurality of values, the value of single pass obviously cumbersome, method, can be passed to the distal end by about locals () functions in the all parameters:

def index(request):
  return render(request,'reg.html',locals())

  虽然locals()方法可以一劳永逸,但是会浪费资源,会传递前端不要的参数。

  传入的值如果数python的数据类型几乎都可以被渲染,但是也有特殊的:

  1.函数。

  如果传函数名,会自动加括号调用该函数,前端展示的是函数调用之后的返回值。

  注意:如果函数需要参数的话 那么模板语法不支持。

  2.类。

  如果将类实例化对象传给前端,会将该对象的内存地址传入,前端页面可以通过该对象名点出其中的函数方法和变量。

  其中的函数也不支持传参。

  模板语法:

  {{}} 变量相关。

  {%%}语法相关。

五。模板语法过滤器。

  过滤器的固定语法是:

{{ 变量名|过滤器名 }}

  其内部原理是,将|前面的变量名当成过滤器的第一个参数传入。

@register.filter(is_safe=False)
def length(value):
    """Returns the length of the value - useful for lists."""
    try:
        return len(value)
    except (ValueError, TypeError):
        return 0

  如果不支持该过滤器,会返回0

 1。{{ l|length }}

  统计l的长度。

  2。{{ ss|default:'当|左边的变量为空就会返回|右边的值' }}

  如果ss存在,则返回ss,如果为空则返回default,如果ss不存在也返回他,和get很像。

  3。{{ file_size|filesizeformat }}

  将file_size转换成文件大小。

  4。{{ info|truncatewords:3 }}

  按照空格将info文字进行截断,3是截断的个数。

  5。{{ info|truncatechars:6 }}

  按照字符截取info,点也算,也就是至少传入3。

  6。{{ xxx|safe }}

  一般的,xxx字符串传入前端后,直接以字符串的形式传入,但是加上safe之后,就会将xxx按照原来的意思进行输入,如果该字符是页面元素,会显示页面元素。

  后端可以取消这个机制:

from django.utils.safestring import mark_safe
zzz=make_safe('内容')

  7.{{ ctime|date:'Y-m-d H-i-s' }}

  如果后端传来的ctime是一个时间类型的数据,那么可以通过过滤器date进行渲染。

  8.{{ n|add:100 }}

  将n数字加100,如果是字符串,则拼接字符串。

  9.{{ l|slice:'0:5:2' }}

  将1切片,故头不顾尾,支持步长

六。模板层之标签。

  标签也就是逻辑相关的操作,使用{% %}

  1.forloop。

  在for循环中,这个标签可以记录for循环的一些值:

{% for foo in l %}
    <p>{{ forloop }}</p>
{% endfor %}

  如图:

 

 

   2.{%empty%}

  当for 循环为空,则执行这个标签下的方法。

  3.if判断:

{% if '' %}
<p>xxx条件为true</p>
    {% else %}
    <p>xxx条件为false</p>
{% endif %}

  4.点。

  django模板语法在取值的时候 统一使用句点符。如:

{ l.6.3.name }

  5.{%with 数据 as 别名%}

  可以通过这个标签给数据取别名,这样可以方便操作。在with中就可以使用该别名。

    {% with l.6.3.name as ttt %}  
        {{ ttt }}
        {{ l.6.3.name }}
    {% endwith %}

  6.for循环中字典的三个方法:

{% for foo in d.keys %}
    <p>{{ foo }}</p>
{% endfor %}
{% for foo in d.values %}
    <p>{{ foo }}</p>
{% endfor %}
{% for foo in d.items %}
    <p>{{ foo }}</p>
{% endfor %}

七。自定义过滤器与标签。

  自定义的东西需要遵循下面三个步骤:

  1.必须在你的应用下新建一个名为templatetags文件夹

  2.在该文件夹内新建一个任意名称的py文件

  3.在该py文件中固定先写下面两句代码

    from django import template

    register = template.Library()

  然后就可以在这个文件下面编写字节的过滤器了:

@register.filter(name='baby')
def index(a,b):
    # 该过滤器只做一个加法运算  是|add简易版本
    return a + b

  定义的时候需要给它取个别名,然后要阿紫网页中调用该过滤器。

{% load mytag %}
{{ 123|baby:1}}

  其中mytag是template下的文件名,baby是起的名字。

  注意,自定义guolq只能指定两个形参,但是第二个参数可以是一个列表。

  自定义标签

  标签的定义方法和guolvq差不多:

@register.simple_tag(name='jason')
def xxx(a,b,c,year):
    return '%s?%s|%s{%s'%(a,b,c,year)

  但是标签支持传入多个参数,标签的使用:

支持传多个参数  参数与参数之间 空格隔开即可、
{% load mytag %}
{% jason 1 2 3 year=2 %}

  也支持关键字传参。

  自定义inclusion_tag

  这个工作原理是接受用户传入的参数,然后根据参数渲染出一个页面,再返回到调用inclusion_tag的地方。

  定义方法:

# 自定义inclusion_tag
@register.inclusion_tag('bigplus.html')
def bigplus(n):
    l = []
    for i in range(n):
        l.append('第%s项'%i)
    return {'l':l}

  它需要指定一个页面,这个页面是要被调用的页面,会接受这个函数返回的值。

 

   调用:

{% load mytag %}
{% bigplus 5 %}

  应用场景:

  可以定义一个多次运用的页面,可以反复调用。

八。模板的继承和导入。

  继承:

  当多个页面整体的样式都大差不差的情况下 可以设置一个模板文件。

  在该模板文件中 使用block块划分多个预期。

  之后子版在使用模板的时候 可以通过block块的名字 来选定到底需要修改哪一部分区域

  也就是说,母模板中可以将需要改变的地方通过{% block css%}  {% endblock%}划分页面。

{% block css %}
    子页面自己的css代码
{% endblock %}            
{% block content %}
    子页面自己的html代码
{% endblock %}
{% block js %}
    子页面自己的js代码
{% endblock %}

  这个名字是自己定义的。

  在其他页面可以继承这个母模板进行复用:

# 模板的继承  使用方式
{% extends 'home.html' %}

{% block css %}
    <style>
        h1 {
            color: red;
        }
    </style>
{% endblock %}

  通过{{ block.super}} 也可以获得目标签该区域的元素

  一般情况下 模板上的block越多 页面的可扩展性就越强。

  模板的导入:

{% include 'beautiful.html' %}

  将一个静态的页面,通过导入的方式加入模板。

 

 

 

 

 

 

 

 

 

补充:

  1.如果一个类中的函数时绑定类方法,而使用对象调用,会获取对象的类,当成第一个参数传入。

  2。通过字符串导入模块的方法:

import importlib
mod = importlib.import_module(从哪个模块中,’所调用的模块的字符串‘)

 

Guess you like

Origin www.cnblogs.com/LZXlzmmddtm/p/11545993.html