1126 Class Summary view layer template layer

A, layer view (view)

View function, the function is essentially a python, he accepts web request and return a response. Response content can be HTML pages, redirects, 404 errors anything, but essentially returns a HttpResponse object . View function convention to write view.py the paper

Second, the request object -HttpRequest

Some common attribute request object

When a page is requested, the request requesting Django row packets, the header information, relating to the contents of the package into HttpRequest class attributes.
Django This object will be automatically passed to the view response function, general view function using convention request parameter receiving object.

1. request.method           #方式,返回的是纯大写的字符串。

2. request.GET              #获取用户提交的get请求数据,返回的是列表套对象。
3. request.GET.get()        #获取列表中的最后一个
4. request.GET.getlist()    #获取列表类型的数据

5. request.POST             #获取用户提交的post请求数据
6. request.POST.get()       #获取列表中的最后一个
7. request.POST.getlist()   #获取列表类型的数据

8. request.FILES            #包含所有的上传文件信息。

Note: Method FILES only from a form POST request is submitted and with enctype="multipart/form-data"the case where the data will be included. Otherwise, FILES will be a blank dictionary-like object.

Third, the response object -HttpResponse

In response to a variety of forms, it can be HTML pages, redirects, 404 errors anything, but essentially returns a HttpResponse object . Specifically response object There are three main forms: HttpResponse, render, redirect

3-1. HttpResponse()

The HttpResponse () parenthesis directly with a particular character string as a response thereof. That returns the string

3-2. render()

render(request,template_name,[context])

parameter:

  • request: a request for an object that generates the response.
  • template_name: To use the template name.
  • context: add a dictionary to the template context. Default empty dictionary, a dictionary if a value is callable, the view will be called before rendering the template.

approach is to render a template syntax template page rendering, final rendering into a html page as response body.

3-3. redirect()

Deliver a hard-coded to redirect the URL, the URL of the file that is local

def my_view(request):
    ...
    return redirect('some/url')

It can be a complete URL:

def my_view(request):
    ...
    return redirect('http://www.baidu.com')

Four, JsonResponse

Returns a json format string in two ways to the distal end

# 第一种方式
import json
def my_view(request):
    data=['xxx','yyy']
    return HttpResponse(json.dumps(data))

# 第二种方式
from django.http import JsonResponse
def my_view(request):
    data = ['xxx', 'yyy']
    return JsonResponse(data1,safe=False)
# 默认safe=True代表 只能序列化字典,safe=False代表可以序列化其他数据类型

Five, FBV and CBV

View FBV function (Function base view) based

CBV is a view (Class base view) class-based

# FBV
# FBV视图层书写方式
def login(request):
    print('我是login函数')
    return render(request,'login.html')


# FBV路由层的书写
url(r'^index/',views.index),



# CBV
# CBV视图层书写方式
from django.views import View
class MyLogin(View):
    def get(self,request):
        print('我是MyLogin里面的get方法')
        return render(request,'login.html')

    def post(self,request):
        print('我是MyLogin里面的post方法')
        return HttpResponse('post')
# CBV路由层的书写
url(r'^login/',views.MyLogin.as_view())

Sixth, to increase CBV decorator

# 第一种方法:直接书写
class MyLogin(View):
    @outter  # 1.直接写
    def get(self,request):
        print('我是MyLogin里面的get方法')
        return render(request,'login.html')
    @outter  # 1.直接写
    def post(self,request):
        print('我是MyLogin里面的post方法')
        time.sleep(1)
        return HttpResponse('post')


# 第二种使用内置函数,推荐方法
from django.utils.decorators import method_decorator

# 1-1. 内置函数也可以在外面写,并且可以指定给谁装
@method_decorator(outter,name='post')
class MyLogin(View):
    @method_decorator(outter)  # 1-2. 推荐写法
    def get(self,request):
        print('我是MyLogin里面的get方法')
        return render(request,'login.html')

    def post(self,request):
        print('我是MyLogin里面的post方法')
        time.sleep(1)
        return HttpResponse('post')


# 第三种内置函数联合重写dispatch方法

from django.utils.decorators import method_decorator

class MyLogin(View):
    @method_decorator(outter)
    def dispatch(self, request, *args, **kwargs):  
        # 如果你想在视图函数执行之前 做一些操作 你可以在你的CBV中定义dispatch方法来拦截
        return super().dispatch(request,*args,**kwargs)
  
    def get(self,request):
        print('我是MyLogin里面的get方法')
        return render(request,'login.html')
    def post(self,request):
        print('我是MyLogin里面的post方法')
        time.sleep(1)
        return HttpResponse('post')

----------------------------------------------------------

First, the template layer (template)

Stored in template folder html files called template file, the template grammar can be displayed using dynamic data in html, simply Django = HTML template code for the template grammar +

Second, the template syntax of a comment

{# this won't be rendered #}  单行注释

注释多行使用comment标签

Third, the template syntax of variables

Key traversing complex data structures in django template is a period character , the syntax: {{name}} variable . Variables in python similar to variable.

Named variables include any alphanumeric and underscore ( "_") combination. Point ( ".") Is also likely to occur in the variable name, but it has a special meaning. Note: The most important is that variable names can not contain spaces or punctuation.

views.py:

name='abc'
age=18
li=[1,2,'3','4']
dic={'name':'abc','age':18,''li:[1,2,4]}
def test():   #函数
    print('abc')
    return 'abchahahah'
class Person():
    def __init__(self,name,age)
        self.name=name
        self.age=age
    def get_name(self):
        return self.name
    @classmethod
    def cls_test(cls):
        return 'cls'
    @staticmethod
    def static_test():
        return 'static'
    ---------
    # 模板里不支持带参数
    def get_name_cs(self,ttt):
        return self.name
    ----------
    
xxx=Person('xxx',18)
yyy=Person('yyy',28)
person_list=[xxx,yyy]

html:

Equivalent to print the variable

<p>字符串:{{ name }}</p>
<p>数字:{{ age }}</p>
<p>列表:{{ li }}</p>
<p>元祖:{{ tu }}</p>
<p>字典:{{ dic }}</p>
<p>函数:{{ test }}</p>  {#只写函数名:相当于函数名(),返回函数执行结果#}
<p>对象:{{ xxx }}</p>   {#对象内存地址#}

Depth inquiry:

<p>列表第1个值:{{ ll.0 }}</p>
<p>列表第4个值:{{ ll.3 }}</p>
<p>字典取值:{{ dic.name }}</p>
<p>字典取列表值:{{ dic.li }}</p>
<p>对象取数据属性:{{ xxx.name }}</p>
<p>对象取绑定给对象的函数属性:{{ xxx.get_name }}</p>
<p>对象取绑定给类的函数属性:{{ xxx.cls_test }}</p>
<p>对象取静态方法:{{ xxx.static_test }}</p>

Fourth, the label template syntax

Some create text in the output, some additional information to control the process cycle or by logic, some variables will be used to load subsequent to the template. Some labels need to start and end tag syntax {% tagname%}

The value of template syntax uses only one way to unify a period character (.)

4-1. For loop

# 遍历每一个元素
{% for person in person_list %}
    <p>{{ person }}</p>
{% end for%}


# 遍历一个字典:
{% for k,v in dic.items %}
    <p>{{ k }}:{{ v }}</p>

The following are some of the attributes for the label Django built-in, you can use the same variables as {{ }}used in the template.

  • forloop.counter: index of the current cycle, counting from the beginning; commonly employed to form a list or table number

  • forloop.counter0: circulating current index value, counted from 0;

  • forloop.revcounter: the number of times the end of the cycle (starting from 1)

  • The number of end forloop.revcounter0 cycle (starting from 0)

  • forloop.first: determine whether the current cycle is the first time, that is the case, the variable value is True. We often the first line of treatment for a particular plus point, the lingua franca of this judgment, in conjunction with if.

  • forloop.last: If this is the last cycle, True

  • forloop.parentloop: For the nested loop, returns the number of cycles where the parent cycles

4-2. for...empty

for a label with optional {% empty %}clause, group operations performed is given when empty or not found

Note: The cycle of the object is empty, it will go empty, rather than the object stuff inside is empty

{% for person in person_list %}
    <p>{{ person.name }}</p>
    {% empty %}
    <p>sorry,no person here</p>
{% endfor %}

4-3. If judgment

{% if %}Have a variable evaluation, if its value is "True" (exists, is not empty, and not false boolean value type), the block will output the corresponding content.

{% if num > 100 or num < 0 %}
    <p>无效</p>
{% elif num > 80 and num < 100 %}
    <p>优秀</p>
{% else %}
    <p>良好</p>
{% endif %}

Note: Use brackets if the label is incorrect syntax, this statement is different from Pythonif support, priority may be used if nested. if support and, or, ==,>, <,! =, <=,> =, in, not in, is, is not to judge.

4-4. Examples of labels

# 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 %}
        
    
# 模板语法的取值 只有一种方式  统一采用句点符  (.)
comp_dic = {'username':'jason','hobby':['read','study',['run','rap',{'age':18}]]}
# 获取字典嵌套中的age
<p>{{ comp_dic.hobby.2.2.age }}</p>

Fifth, the filter template syntax

In Django template language by using filters to change the display of variables. The syntax of the filter: {{value | FILTER_NAME: Parameter}}

Precautions :

  1. Filter supports the "chain" operation. I.e., a filter output as input to another filter.
  2. Filters can accept parameters, a parameter can accept
  3. Filter parameter contains a space, it must be wrapped in quotes. Such as comma and a space used to connect the elements of a list, such as: {{list | join: ','}}
  4. '|' Around with no spaces

Common filter

1. default

<!-- 如果变量是false或者为空,则使用给定的默认值。-->
{{ value|default:'nothing'}}

2. length

<!-- 返回值的长度,对字符串和列表都起作用-->
value=[1,2,3,4]  
{{ value|length}}   输出是4

3. filesizeformat

<!-- 将值格式化成'人类可读的'文件尺寸。-->
{{1024|filesizeformat}}  输出为1kb

4. safe

<!-- Django模板为了安全默认会对HTML标签和js等语法标签进行转义,有时候我们不希望这些元素被转义,可以通过设置过滤器。-->
script="'<script>alert(111)</script>"
{{ script|safe }}



# 补充:后端也可以利用模块取消转义
from django.utils.safestring import mark_safe
sss2 = "<h2>我的h2标签</h2>"
res = mark_safe(sss2)

5.slice

<!-- 切片,不支持负数 -->
{{ name|slice:'0:3:3' }}

6.truncatechars

<!-- 如果字符串多余指定字符数量,多余会被截断,替换成("...")结尾。 -->
{{ value|truncatechars:9}}

7.truncatewords

<!-- 在一定数量的字后截断字符串。-->
{{ value|truncatewords:9}}

Six, custom tags and filters

6-1. Custom pre-prepared

  1. In the name of the application (app folder) to create a new templatetagspackage (name fixed), and views.py, models.py and other files in the same directory

  2. Create a new folder any name in the file .py file, such as:my_tags.py

  3. You must write the code in the following two .py file

    from django.template import Library
    register = Library()

6-2. Custom filter

Since python function definition is actually a filter having one or two parameters

NOTE: The first parameter is a function of the object to be filtered, a second custom parameter, a total of only two function parameters.

  • The value of the variable: not necessarily a string
  • There may be an initial value, or do not need this parameter
# 自定义过滤器  跟默认的过滤器一样 最多只能接受两个参数
# 利用register.filter注册并给该过滤器起别名
@register.filter(name='baby')
def index(a,b):
    return a + b


# 自定义过滤器的使用
# 在要使用自定义过滤器的模板文件中导入创建的py文件。语法:{% load 文件名 %}
{% load mytag %}
{{ 1|baby:1  }}
{{ 1|baby:100  }}

# 自定义的过滤器可以在逻辑语句使用 而自定义的标签不可以
{% if mytag '1' '2' '3' '4' %}
    <p>有值</p>
{% else %}
    <p>无值</p>
{% endif %}#

6-3. Custom Labels

In addition decorator, other steps similar to the custom filter.

Only two filter parameters, custom labels may pass a plurality of values, value-passing spaces.

Note: if the filter can be used in the determination, labels can not

# 自定义标签   可以接受任意多个参数
# 利用register.simple_tag()注册并给该标签起别名

@register.simple_tag(name='mytag')
def mytag(a,b,c,d):
    return '%s?%s?%s?%s'%(a,b,c,d)

# 自定义标签的使用 可以接受多个参数 参数与参数之间必须空格隔开
{% load mytag %}
    {% mytag 'a' 'b' 'c' 'd' %}

6-4. Custom 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页面
    
# 自定义inclusion_tag的使用  当你需要使用一些页面组件的时候 并且该页面组件需要参数才能够正常渲染 你可以考虑使用inclusion_tag</p>
{% load mytag %}
    {% xxx 5 %}

Seven, inherited template

You can create a basic template inheritance "skeleton" template that contains all the elements of the site, and can be defined template quilt blocks can covered

note:

  1. The stronger the more scalable template block area on a page, a page template preferably has three regions: css region, html code region, js html region may be provided a plurality of regions block. With these three areas will be able to implement each page has its own separate css and js code
  2. You can not define multiple block tags with the same name in a template
  3. If you use the template {% extends %}label, it must be the first label template
# 子模板login.html继承index.html文件模板,全部继承的情况下无法修改内容
# 即login.html中只需要写一句代码
{% extends 'home.html' %}


# 如果子模板需要修改部分,就需要用到 block
# 母模板 index.html
...
<body>
<div id="sidebar">
    # 划定这块区域可以修改,并取别名sidebar
    {% block sidebar %}
        <ul>
            <li><a href="/">Home</a></li>
            <li><a href="/blog/">Blog</a></li>
        </ul>
    {% endblock %}
</div>
<div id="content">
    # 划定这块区域可以修改,并取别名content
    {% block content %}{% endblock %}
</div>



# 子模板 login.html
{% extends 'home.html' %}

# 使用block,pycharm会自动提示有哪些区域
{% block sidebar %}
    ...修改内容
</style>
{% endblock %}

{% block content %}
    ...修改内容
{% endblock %}

Eight, the import template

To solve a simple template statement repeated assembly code redundancy

Syntax: {% include 'template name'}%

# 做好注册前提准备,简单的代码可以直接运行imp路径
# imp.html文件内容
{% include 'fr.html' %}

# fr.html文件内容
<p>这是一个特别好看的form表单</p>

Guess you like

Origin www.cnblogs.com/faye12/p/11938322.html
Recommended