Django — template layer (front end and back end interactive coding, two methods used by Django template, variable of template syntax & deep query period, rendering template to label or original string, filter + custom, label + custom)

Time:2021-1-14

1、 Front end and back end interactive coding mode

1 urlencoded --- > transfers common data, which is the default form -- > request.POST
2 form data -- > transfer files and data -- > request.POST    request.FILES
3 JSON -------- transfer JSON format data -- > request.body Take it out and handle it by yourself

def index(request):
    #Receive urlencoded code
    In the body: name = Lili & age = 18
    # print(request.POST)

    #Receiving form data encoding
    Body: it is divided into two parts, one is data, the other is file
    Data part: name = Lili & age = 18
    ---asdfasdfasdfgasgasgd---
    File part (binary)
    
    #Data section
    # print(request.POST)
    #Document section
    # print(request.FILES)

    #Receiving JSON format
    In the body 
    {
    "name": "lili",
    "age": 18
    }
    #Not here
    print(request.POST)
    #The data is here
    print(request.body)


    return HttpResponse('ok')

2Two ways of using Django template

#Mode one
return render(request,'time.html',context={'current_date':str(now),'title':'lqzNB'})

#Mode 2 (page static, improve the concurrency of the website)
    now=datetime.datetime.now()
    from day65 import settings
    import os
    path=os.path.join(settings.BASE_DIR,'templates','time.html')
    ss=open(path,'r',encoding='utf-8').read()
    t=Template(ss)
    c=Context({'current_date':str(now),'title':'lqzNB'})
    HTML = T. render (c) # html is the rendered string
    return HttpResponse(html)

3Variables in template syntax

DTL: Django template language

#views.py

1 template using {Python variables}}

def index(request):
    num = 10
    ss = 'lqz is handsome'
    b = False
    ll = [1, 2, 43]
    dic = {'name': 'lqz', 'age': 18}

    def test():
        Print ('I'm test ')
        Return 'test --- launch point'

    class Person():
        def __init__(self, name):
            self.name = name

        def print_name(self):
            return self.name
        def __str__(self):
            return self.name

    p=Person('lqz')

    # return render(request, 'index.html',{'num':num,'ss':ss,'b':b})
    #Locales () transfers all variables in the current scope to context
    return render(request, 'index.html',locals())
# index.html
{{ss}}



Variables in template syntax

Number: {num}}
String: {SS}}
Boolean: {B}}
List: {ll}}
Dictionary: {DIC}}
Function: {test}}
Object: {P}}

4、 Deep query period in template syntax

# views.py

def index(request):
    num = 10
    ss = 'lqz is handsome'
    b = False
    ll = [1, 2, 43, {'name': 'egon'}]
    dic = {'name': 'lqz', 'age': 18}

    def test():
        Print ('I'm test ')
        Return 'test --- launch point'

    class Person():
        def __init__(self, name):
            self.name = name

        def print_name(self):
            return self.name

        def __str__(self):
            return self.name

    p = Person('lqz')

    Link1 ='point me '

    link2 = mark_safe(link1)

    input_ 1 ='user Name: '
    input_2=mark_safe(input_1)


    script_1='''
    
    Alert ('You've been attacked ')
    
    '''
    script_2 =mark_safe(script_1)
    return render(request, 'index.html', locals())

index.html

Deep query of period in template syntax
The first element of the list: {LL. 1}
Corresponding value of dictionary name:{{ dic.name  P
The value corresponding to the name of the third element in the list: {LL. 3. Name}}
Function execution, write the function name directly: {{test}}
If the function has parameters? I won't support it
Object calling method: {p.print_ name }}
Object call property: {p.name}

Point me
String of a tag: {link1}}
The string of a tag is displayed as a tag: {link2}}

user name:
Input tag: {input}_ 1 }}
Input tag, displayed as tag: {{input}_ 2 }}

JS is displayed intact: {{script}_ 1 }}

{{ script_2 }}

5、 It showsDoes the template render as a label or as is string

#Here is where XSS attacks appear # XSS attacks: what are they and how to prevent them? Django has already dealt with XSS attack. What is its principle

from django.utils.safestring import mark_safe
Link1 ='point me '

link2 = mark_safe(link1)

{link1|safe}

6、 OverFilter

default,length,filesizeformat,date,slice,truncatechars,safe

1 {{parameter 1 | filter name: parameter 2}
2 filter can pass at most two values, and at least one value {{{lqz is' | slice: '2:3'}}


#Understanding
Filesizeformat of filter: {{num | filesizeformat}}
lqz is handsome
Slice of filter: {{SS | slice: "7:11"}}
The second parameter is 0, 1, 2, all of which are... At least starting from 3
Truncatechars of filters: {{SS | truncatechars: '30'}}
truncatewords:{{ ss|truncatewords:'2' }}
#Remember
Date of the filter: {{CTime | date:'m, D, Y - --- h, I, min, s'}}
Filter's safe: {{link1 | safe}}

7、 Custom filter

 

Custom filter
    -Step 1: installed in settings_ Apps configures the current app, otherwise Django cannot find the custom simple_ Tag
    -Step 2: create a templatetags package in the app (the package name can only be templatetags and cannot be changed)
    -Step 3: create a new py file (such as my_ tags.py )
    -Step 4: write code (filter)
        from django import template
        register = template.Library()
        @register.filter
        def my_upper(value):
            return value.upper()
    -Step 5 use: (template), load first, then use
        {% load my_tags %}
        {{ 'aa'|my_upper }}

 

8、 Label

for,for … empty,if,with,csrf_token

1 {% tag name%}

2 label for. There is always a forloop object inside the label for, which is a dictionary
Counter 0: starting from 0, add 1 to each cycle
Counter: start from 1 and add 1 to each cycle
Revcounter: start with the length of the list and subtract one from each loop
First: judge whether it's the first step of the cycle
Last: judge if it's the last one in the cycle
Parentloop: parent forloop object (nested for loop)
{'parentloop': {}, 'counter0': 0, 'counter': 1, 'revcounter': 6, 'revcounter0': 5, 'first': True, 'last': False}

3 if tag

4 with label (understanding)
5 CSRF tag (understanding)

#views.py

def index(request):
    ll=['lqz','egon','zs','ls','ww']
    # ll=[]
    dic={'name':'lqz','age':19}
    count=1

    lqzisnbplus='lqz'
    # b=False
    b=True
    user_ List = [{name ':'lqz','age ': 19}, {name':'egon ','age': 18}, {name ':'zhang San','age ': 22}, {name':'li Si ','age': 99}, {name ':'asdfasdf','age ': 18}, {name':'dark room Fengdeng n ','age': 18}]
    return render(request, 'index.html', locals())

 

#index.html

Label of template syntax

Usage of for
{% for l in ll %}
    {#    {{ l }}#}
    {{ l }}
{% endfor %}


{% for k,v in dic.items %}
    The key value is: {{K}} and the value is {{V}}
{% endfor %}


    
        ID number
        user name
        Age
    
    {% for dic in user_list %}
        
            {{ forloop.counter }}
            {{ dic.name }}
            {{ dic.age }}
        
    {% endfor %}




The usage of for --- empty

    {% for l in ll %}
        {{ l }}
    {% empty %}
        no data
    {% endfor %}


Forloop object
{% for dic in user_list %}



    {% for key,value in dic.items %}
        {{ forloop.parentloop.counter }}
        {{ key }}:{{ value }}
    {% endfor %}

{% endfor %}

if

{% if b %}
    B is true
{% else %}
    B is false
{% endif %}


With rename


{% with forloop.parentloop.counter as aaa %}
    {{ aaa }}
{% endwith %}


{% with lqzisnbplus as a %}
{{ a }}
----{{ lqzisnbplus }}

{% endwith %}


csrf

{% csrf_token %}