View template rendering filter (built-in) label

Content Today

  1. view
  2. Plus view decorator
  3. Template Rendering
  4. Filter (built)
  5. label

view

A view function (class), referred to as a view, Python is a simple function (class) that accepts the request and returns Web Web response.

The response may be a page's HTML content, a redirect, a 404 error, an XML document, or a picture

No matter what the view itself contains logic, it must return a response. Write the code where it does not matter, as long as it is in your current directory project. In addition to the requirements of no more

FBV and CBV view

The FBV (function class)

FBV (function base views) is to use the processing functions in the view request.

from django.shortcuts import render,HttpResponse,redirect
def cs(request):
    return redirect('/cs1/')  #重定向  redirect(路径)

CBV (Object)

CBV (class base views) is used in the view request handling.

The final step Source

 http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']

def dispatch(self, request, *args, **kwargs):
    # Try to dispatch to the right method; if a method doesn't exist,
    # defer to the error handler. Also defer to the error handler if the
    # request method isn't on the approved list.
    if request.method.lower() in self.http_method_names:#实现分发的
        handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
    else:
        handler = self.http_method_not_allowed
    return handler(request, *args, **kwargs)

We can perform our logic analysis prior to distribution by source

from django.views import View
class LoginView(View):
    # def dispatch(self, request, *args, **kwargs):
    #     print('xx请求来啦!!!!')请求来之前  但不知道是什么方法前执行
    #     ret = super().dispatch(request, *args, **kwargs)
    #     print('请求处理的逻辑已经结束啦!!!')
    #     return ret
    def get(self,request):  #处理get请求直接定义get方法,不需要自己判断请求方法了,源码中用dispatch方法中使用了反射来处理的
        print('小小小小')
        return render(request,'login.html')

    def post(self,request):
        print(request.POST)
        return HttpResponse('登录成功')

urls.py routing wording

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

Plus view class decorator

Decorator decoration FBV

FBV is itself a function, and it is common to add a function of decorator no difference

def wrapper(func):
    def inner(*args, **kwargs):
        start_time = time.time()
        ret = func(*args, **kwargs)
        end_time = time.time()
        print("used:", end_time-start_time)
        return ret
    return inner


# FBV版添加班级
@wrapper
def add_class(request):
    if request.method == "POST":
        class_name = request.POST.get("class_name")
        models.Classes.objects.create(name=class_name)
        return redirect("/class_list/")
    return render(request, "add_class.html")

Decorator decoration CBV

Method class independent functions are not identical, the method can not be directly applied to a function of decorator class, we need to first convert it to a method decorators. Django provides method_decorator decorative function for converting a method decorator decorators.

第一步先引入模块from django.utils.decorators import method_decorator`
第2步 加语法糖@method_decorator(wrapper)`


from django.shortcuts import render,HttpResponse
from django.views import View
from django.utils.decorators import method_decorator
def wrapper(func):
    def inner(*args, **kwargs):
        print(11111)
        ret = func(*args, **kwargs)
        print(22222)
        return ret
    return inner

# @method_decorator(wrapper,name='get')  # 方式3给get加 用的不多
class LoginView(View):

    @method_decorator(wrapper)  #方式1
    def get(self,request):
        print('小小小小')
        return HttpResponse('登录成功')

    def post(self,request):
        print(request.POST)
        return HttpResponse('登录成功')

The request object

Django This object will be automatically passed to the view response function, general view function using convention receiving the object request parameter.

 Official Documents

 Common values ​​related requests

  • path_info return the user to access url, not including the domain
  • method string HTTP method used in the request indicates, represents all uppercase.
  • GET contain dictionary-like object all HTTP GET parameters
  • POST dictionary-like object containing all the HTTP POST parameters
  • body request body, byte type request.POST data is extracted from inside the body to

Attributes

When the get request input URL http://127.0.0.1:8000/cs/??a=1&b=2

def cs(request):
    print(request)  #<WSGIRequest: GET '/cs/??a=1&b=2'>
    print(request.path) #/cs/ 纯路径
    print(request.path_info) #/cs/ 纯路径
    print(request.get_full_path())#/cs/??a=1&b=2全路径 (不包含ip地址和端口)
    print(request.META)  #请求头相关数据,是一个字典
    print(request.method)  #GET
    print(request.GET)#<QueryDict: {'?a': ['1'], 'b': ['2']}>
    print(request.POST)#<QueryDict: {}>
    print(request.body) #能够拿到请求数据部分的数据(post,get没有) b''
    return HttpResponse('666')

Enter the URL http://127.0.0.1:8000/cs/

def cs(request):
    print(request)  #<WSGIRequest: GET '/cs/??a=1&b=2'>
    print(request.path) #/cs/ 纯路径
    print(request.path_info) #/cs/ 纯路径
    print(request.get_full_path())#/cs/??a=1&b=2全路径 (不包含ip地址和端口)
    print(request.META)  #请求头相关数据,是一个字典
    print(request.method)  #POST
    print(request.GET)#<QueryDict: {}>
    print(request.POST)#<QueryDict: {'a': ['1'], 'b': ['2']}>
    print(request.body) # b'a=1&b=2'  能够拿到请求数据部分的数据(post,get没有) 
    return render(request,'cs.html')

a box to enter the input frame 1 b 2

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="" method="post">
    a<input type="text" name="a">
    b<input type="text" name="b">
    <input type="submit">
</form>
</body>
</html>

Response object

from django.shortcuts import render,HttpResponse,redirect
HTTPResponse('字符串') #返回字符串
render(request,'xx.html')#返回html页面

redirect 重定向
def cs(request):
    return redirect('/cs1/')  #重定向  redirect(路径)

def cs1(request):
    return HttpResponse('666')

Rendering template syntax

Template rendering of official documents

Variable associated with {{}}, {logic associated with %%}.

{{ 变量 }}   {% 逻辑 %} -- 标签

variable

Click Django template language syntax used in: {{name}} variable.

When the template engine encounters a variable, it will calculate the variable, and then replace it with the result itself. Named variables include any alphanumeric and underscore ( "_") combination. Variable names can not contain spaces or punctuation.

We can use the depth inquiry stronghold symbol (.) Query

Everything points to get the value

views.py view function wording

from django.shortcuts import render
def home(request):
    import datetime
    current_time = datetime.datetime.now()
    name = '小白'
    num = 101
    d1 = {'xx':'oo','xx2':'oo2','xx3':[11,22,33]}
    d2 = ['11','22','33']
    d3 = []
    l1 = ['李业','陈硕','王洋','海狗']
    class Person:
        n = '类的属性'
        def p(self):
            return '类p的返回值'
    obj = Person()
    return render(request,'home.html',{'name':name,'d1':d1})

HTML pages written

注意字典 列表 和对象中方法

<h2>{{ name }}</h2>
<h2>{{ d1.items }}</h2>items keys vlues
<h2>我是"{{ l1.1 }}"</h2>
<h2>{{ num }}</h2>
<h2>{{ obj.p }}</h2>  #如果调用的方法需要传参,sorry用不了

Filter (built)

The syntax of the filter: {{value | filter_name: Parameter}}

Use pipe symbol "|" applying a filter.

Precautions:

  1. Filter supports the "chain" operation. I.e., a filter output as input to another filter.

  2. Filters can accept parameters, for example: {{sss | truncatewords: 30}}, which will display the first 30 words of sss.

  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 is no space without a space with no spaces

参考博客:https://www.cnblogs.com/clschao/articles/10414811.html
default 如果一个变量是false或者为空,使用给定的默认值。 否则,使用变量的值。
{{ value|default:"nothing"}}
如果value没有传值或者值为空的话就显示nothing

length返回值的长度,作用于字符串和列表。
{{ value|length }}
返回value的长度,如 value=['a', 'b', 'c', 'd']的话,就显示4.

filesizeformat将值格式化为一个 “人类可读的” 文件尺寸 (例如 '13 KB', '4.1 MB', '102 bytes', 等等)。
{{ value|filesizeformat }}
如果 value 是 123456789,输出将会是 117.7 MB。

slice
切片,如果 value="hello world",还有其他可切片的数据类型
{{value|slice:"2:-1"}}

date格式化,
value=datetime.datetime.now()
{{ value|date:"Y-m-d H:i:s"}}
关于时间日期的可用的参数(除了Y,m,d等等)还有很多,有兴趣的可以去查查看看。

safe
{{ value|safe}}
如果value = "<a href='#'>点我</a>"   那么页面显示的是a标签

truncatechars如果字符串字符多于指定的字符数量,那么会被截断。截断的字符串将以可翻译的省略号序列(“...”)结尾。
{{ value|truncatechars:9}} #注意:最后那三个省略号也是9个字符里面的,也就是这个9截断出来的是6个字符+3个省略号,有人会说,怎么展开啊,配合前端的点击事件就行啦

truncatewords在一定数量的字后截断字符串,是截多少个单词。
例如:‘hello girl hi baby yue ma’,
{{ value|truncatewords:3}}  #上面例子得到的结果是 'hello girl h1...'

cut移除value中所有的与给出的变量相同的字符串

{{ value|cut:' ' }}
    如果value为'i love you',那么将输出'iloveyou'.

join使用字符串连接列表,{{ list|join:', ' }},就像Python的str.join(list)
 

Tags Tags

Format {% tag %}label content ...{% endtag %}

for labels

Generate several p tag

{% for person in person_list %}
    <p>{{ person.name }}</p>  <!--凡是变量都要用两个大括号括起来-->
{% endfor %}

Reverse circulation

{% for obj in list reversed %}

Traversing a dictionary:

{% for key,val in dic.items %}
    <p>{{ key }}:{{ val }}</p>
{% endfor %}

forloop

forloop.counter            当前循环的索引值(从1开始),forloop是循环器,通过点来使用功能
forloop.counter0           当前循环的索引值(从0开始)
forloop.revcounter         当前循环的倒序索引值(从1开始)
forloop.revcounter0        当前循环的倒序索引值(从0开始)
forloop.first              当前循环是不是第一次循环(布尔值)
forloop.last               当前循环是不是最后一次循环(布尔值)
forloop.parentloop         本层循环的外层循环的对象,再通过上面的几个属性来显示外层循环的计数等
实列
{% for i in d2 %}
    {% for k,v in d1.items %}

        <li>{{ forloop.counter }}-- {{ forloop.parentloop.counter }} === {{ k }} -- {{ v }}</li>

    {% endfor %}

{% endfor %}

for ... empty

forLabel with an optional {% empty %}clause, through which we can define when the output of the content list is empty

{% for person in person_list %}
    <p>{{ person.name }}</p>
{% empty %}
    <p>你找的东西没有</p>
{% endfor %}

if the label

 {% 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 %}  <!--也是在if标签结构里面的-->
    <p>凑活吧</p>
{% endif %}

if语句支持 and 、or、==、>、<、!=、<=、>=、in、not in、is、is not判断,注意条件两边都有空格。

with

And more for a complex variable to the aliases when you need to use a "trouble" approach (such as database access) many times when it is very useful

方法1
{% with total=business.employees.count %}  #注意等号两边不能有空格
    {{ total }} <!--只能在with语句体内用-->
{% endwith %}
方法2
{% with business.employees.count as total %}
    {{ total }}
{% endwith %}

csrf_token

安全认证机制  
    我们以post方式提交表单的时候,会报错,还记得我们在settings里面的中间件配置里面把一个csrf的防御机制给注销了啊,本身不应该注销的,而是应该学会怎么使用它,并且不让自己的操作被forbiden,通过这个东西就能搞定。

    这个标签用于跨站请求伪造保护,

    在页面的form表单里面(注意是在form表单里面)任何位置写上{% csrf_token %},这个东西模板渲染的时候替换成了<input type="hidden" name="csrfmiddlewaretoken" value="8J4z1wiUEXt0gJSN59dLMnktrXFW0hv7m4d40Mtl37D7vJZfrxLir9L3jSTDjtG8">,隐藏的,这个标签的值是个随机字符串,提交的时候,这个东西也被提交了,首先这个东西是我们后端渲染的时候给页面加上的,那么当你通过我给你的form表单提交数据的时候,你带着这个内容我就认识你,不带着,我就禁止你,因为后台我们django也存着这个东西,和你这个值相同的一个值,可以做对应验证是不是我给你的token,存储这个值的东西我们后面再学,你先知道一下就行了,就像一个我们后台给这个用户的一个通行证,如果你用户没有按照我给你的这个正常的页面来post提交表单数据,或者说你没有先去请求我这个登陆页面,而是直接模拟请求来提交数据,那么我就能知道,你这个请求是非法的,反爬虫或者恶意攻击我的网站,以后将中间件的时候我们在细说这个东西,但是现在你要明白怎么回事,明白为什么django会加这一套防御。

处理反扒
先get请求拿到<input type="hidden" name="csrfmiddlewaretoken" value="8J4z1wiUEXt0gJSN59dLMnktrXFW0hv7m4d40Mtl37D7vJZfrxLir9L3jSTDjtG8">,
name与values 在去请求

Precautions

  1. Django template language does not support continuous judgment that does not support the following wording:
{% if a > b > c %}
...
{% endif %}

Guess you like

Origin www.cnblogs.com/saoqiang/p/11628205.html