Python Advanced-Django Framework-04 Template

Links to the original text: https://www.douban.com/note/622472794/?type=like

Template

As a Web framework, Django provides templates for writing html code. It can also embed template code to complete page development faster and more conveniently. Then, by rendering template in view, the final html string is generated and returned to the client browser. Templates are dedicated to expressing appearance, not program logic. Template design separates business logic view from display content template. A view can use any template, and a template can be used by multiple views.

The template consists of two parts:

  • Static part, including html, css, js.
  • The dynamic part is the template language.

Django Template Language, short for DTL, is defined in the django.template package. After creating the project, the configuration of the template is defined in the project name / settings.py file.

DIRS defines a list of directories, which the template engine searches for in a list order to find template files, usually by creating templates directories under the project's root directory.

Django processing templates are divided into two stages:

  • 1. Loading: Find the template file according to the given path, compile it and put it in memory.
  • 2. Rendering: Use context data to interpolate the template and return the generated string.

To reduce developers'repetition of loading and rendering code, Django provides a shorthand function render for calling templates.

Create a sample project

1) Create project test4.

django-admin startproject test4

2) Enter the project directory test4 and create the application booktest.

cd test4
python manage.py startapp booktest

4) Installation and application of INSTALLED_APPS item in test4/settings.py.

5) In test4/settings.py, the DATABASES item configuration uses MySQL database test2, which has been created in the second part.

6) Find the path of TEMPLATES item configuration template in test4/settings.py.

7) Create template directory structure as follows.

8) Open the test4/urls.py file, including the url configuration of booktest.

9) Create urls.py under booktest/directory and configure url.

from django.conf.urls import url
from booktest import views
urlpatterns=[
    url(r'^$',views.index),
]

10) Open the booktest/views.py file and define the view index.

from django.shortcuts import render

def index(request):
    return render(request,'booktest/index.html')

11) Create the file index.html under the templates/booktest directory, code as follows:

<html>
<head>
    <title>home page</title>
</head>
<body>

</body>
</html>

12) Open the booktest/models.py file and define the model class BookInfo. The structure refers to the second part of the design.

from django.db import models

class BookInfo(models.Model):
    btitle = models.CharField(max_length=20)
    bpub_date = models.DateField()
    bread = models.IntegerField(default=0)
    bcommet = models.IntegerField(default=0)
    isDelete = models.BooleanField(default=False)

 

 

Template Language

Template languages include four types:

  • variable
  • Label
  • Filter
  • Notes

Next, four types are introduced one by one.

Template variables

The role of template variables is to calculate and output. Variable names must be composed of letters, numbers, underscores (not beginning with underscores) and points.

The grammar is as follows:

{{Variable}}

When the template engine encounters a point such as book.title, it will be parsed in the following order:

  • 1. Dictionary book['title']
  • 2. Attribute first method, book as an object, find the attribute title, if there is no method title()
  • 3. If the format is book.0, it resolves to list book[0]

    Insert an empty string''if the variable does not exist.

You cannot pass parameters when calling a method in a template.

Example

1) Open the booktest/views.py file and create the view temp_var.

def temp_var(request):
    dict={'title':'Dictionary key value'}
    book=BookInfo()
    book.btitle='Object attributes'
    context={'dict':dict,'book':book}
    return render(request,'booktest/temp_var.html',context)

2) Open the booktest/urls.py file and configure the url.

url(r'^temp_var/$', views.temp_var),

3) Modify to create temp_var.html under templates/booktest.

<html>
<head>
    <title>Template variables</title>
</head>
<body>
//Template variables: <br/>
{{dict.title}}<br/>
{{book.btitle}}<br/>
</body>
</html>

4) Run the server and enter the following address in the browser.

http://127.0.0.1:8000/temp_var/

5) The browsing effect is as follows.

Label

The grammar is as follows:

{% snippet%}

The for tag syntax is as follows:

{% for item in list%}
Cyclic logic
 {{forloop.counter}} indicates the current number of loops, starting from 1
{%empty%}
Execute this logic when the list is empty or does not exist
{%endfor%}

The if tag syntax is as follows:

{%if ...%}
Logic 1
{%elif ...%}
Logic 2
{%else%}
Logic 3
{%endif%}

The comparison operators are as follows:

Note: The left and right sides of the operator should not be close to variables or constants, but must have spaces.

==
!=
<
>
<=
>=

Boolean operators are as follows:

and
or
not

Click View Built-in label Learn more about tags, and some common tags will be explained in subsequent chapters.

Example

1) Open the booktest/views.py file and create the view temp_tag.

from booktest.models import BookInfo
def temp_tags(request):
    context={'list':BookInfo.objects.all()}
    return render(request,'booktest/temp_tag.html',context)

2) Open the booktest/urls.py file and configure the url.

    url(r'^temp_tag/$', views.temp_tags),

3) Create temp_tag.html under templates/booktest.

<html>
<head>
    <title>Label</title>
</head>
<body>
The list of books is as follows:
<ul>
    {%for book in list%}
        {%if book.id <= 2%}
            <li style="background-color: red;">{{book.btitle}}</li>
        {%elif book.id <= 3%}
            <li style="background-color: blue;">{{book.btitle}}</li>
        {%else%}
            <li style="background-color: green;">{{book.btitle}}</li>
        {%endif%}
    {%empty%}
        <li>Sorry, there are no books.</li>
    {%endfor%}
</ul>
</body>
</html>

4) Run the server and enter the following address in the browser.

http://127.0.0.1:8000/temp_tag/

The browsing effect is as follows:

 

 

Filter

The grammar is as follows:

  • Use pipe symbols | to apply filters for computing, conversion operations, you can use in variables, labels.
  • If the filter requires parameters, use a colon: pass parameters.
Variable | Filter: Parameters

Length length, returns the number of characters in a string, or the number of elements in a list, tuple, or dictionary.

Default value default, returns the default value if the variable does not exist.

data|default:'Default values'

Date date, which is used to format the value of the date type. The commonly used formatting characters are as follows:

  • Y denotes the year, in 4-digit format, and Y denotes the year of two.
  • m means month, format is 01, 02, 12, etc.
  • d denotes the date in the format of 01,02, etc.
  • j denotes the date in the format of 1,2, etc.
  • H denotes the time, 24-digit, and H denotes the time of 12-digit.
  • i is 0-59.
  • s means seconds, 0-59.
value|date:"Y year m month j day  H time i branch s second"

Click View Built-in filter Learn more about filters.

Example

1) Open the booktest/views.py file and create the view temp_filter.

def temp_filter(request):
    context={'list':BookInfo.objects.all()}
    return render(request,'booktest/temp_filter.html',context)

2) Open the booktest/urls.py file and configure the url.

    url(r'^temp_filter/$', views.temp_filter),

3) Create temp_filter.html under templates/booktest.

<head>
    <title>Filter</title>
</head>
<body>
The list of books is as follows:
<ul>
    {%for book in list%}
        {%if book.btitle|length > 4%}
            <li style="background-color: red;">
                {{book.btitle}}
                ---The default time format is:
                {{book.bpub_date}}
            </li>
        {%else%}
            <li style="background-color: green;">
                {{book.btitle}}
                ---The formatting time is:
                {{book.bpub_date|date:"Y-m-j"}}
            </li>
        {%endif%}
    {%endfor%}
</ul>
</body>
</html>

4) Run the server and enter the following address in the browser.

http://127.0.0.1:8000/temp_filter/

The browsing effect is as follows:

 

 

Custom filter

The filter is a function in python. After registration, it can be used as a filter in the template. The following example is to develop a custom filter mod.

Example

1) Create templatetags directory in the application, the current example is "booktest/templatetags", create _init_file, empty content.

2) Create the filters.py file in the "booktest/templatetags" directory, code as follows:

#Import Library class
from django.template import Library

#Create a Library class object
register=Library()

#Register with Decorator
@register.filter
#Define the complement function mod, and find the complement of value 2
def mod(value):
    return value%2 == 0

3) Use custom filters in templates/booktest/temp_filter.html.

  • First, the load tag is used to introduce the module.
{%load filters%}
  • During traversal, parity is determined by number, and the code is changed as follows:

4) Running the server, browsing effect is as follows:

The filter can accept parameters and add mod_num function to booktest/templatetags/filters.py.

#Register with Decorator
@register.filter
#Define the complement function mod_num, and make value complement num
def mod_num(value,num):
    return value%num

5) Modify the traversal time judgment code in templates/booktest/temp_filter.html.

6) Run the server and browse as follows:

 

Notes

Using the following template annotations in the template, this code will not be compiled and output to the client; html annotations can only annotate html content, not the template language.

1) The single-line annotation grammar is as follows:

{#...#}

Annotations can contain any template code, valid or invalid.

{# { % if foo % }bar{ % else % } #}

2) The comment tag is used for multi-line annotations. The grammar is as follows:

{%comment%}
...
{%endcomment%}

 

 

Template Inheritance

Template inheritance and class inheritance have the same meaning, mainly in order to improve code reuse and reduce the workload of developers.

Typical application: Head and tail information of website.

Parent Template

If you find that something is the same in multiple templates, you should define this content in the parent template.

Label block: Used to reserve areas in the parent template, leaving the child template filled with different content, the name can not be the same. For better readability, it is recommended to write a name on the endblock tag, which is the same as the corresponding block name. Data passed in context can also be used in parent templates.

{% block name%}
Reserved area, you can write default content, or no default content
 {% endblock name%}

Subtemplate

Label extends: Inheritance, written in the first line of the sub-template file.

{% extends "Path of parent template"%}

Subtemplates do not need to fill all reserved areas in the parent template. If the subtemplate is not filled, the default values defined by the parent template are used.

Fill in the reserved area of the specified name in the parent template.

{% block name%}
Actual filling content
 {{block.super}} is used to get the content of the block in the parent template
 {% endblock name%}

Example

1) Open the booktest/views.py file and create the view temp_inherit.

def temp_inherit(request):
    context={'title':'Template Inheritance','list':BookInfo.objects.all()}
    return render(request,'booktest/temp_inherit.html',context)

2) Open the booktest/urls.py file and configure the url.

    url(r'^temp_inherit/$', views.temp_inherit),

3) Create inherit_base.html under templates.

<html>
<head>
    <title>{{title}}</title>
</head>
<body>
<h2>This is the head.</h2>
<hr>
{%block qu1%}
This is area one, with default values
{%endblock qu1%}
<hr>
{%block qu2%}
{%endblock qu2%}
<hr>
<h2>This is the tail.</h2>
</body>
</html>

4) Create temp_inherit.html under templates/booktest.

{%extends 'booktest/inherit_base.html'%}
{%block qu2%}
<ul>
    {%for book in list%}
    <li>{{book.btitle}}</li>
    {%endfor%}
</ul>
{%endblock qu2%}

5) Run the server and enter the following address in the browser.

http://127.0.0.1:8000/temp_inherit/

6) The browsing effect is as follows.

 

HTML escape

When the template outputs the context-passed string, the following characters are automatically escaped.

Less than sign < converted to & lt;

Greater than sign > converted to & gt;

Single quotation mark'converted to & # 39;

Double quotation mark "converted to & quot;

And sign-to-amp;

Example

1) Open the booktest/views.py file and create the view html_escape.

def html_escape(request):
    context={'content':'<h1>hello world</h1>'}
    return render(request,'booktest/html_escape.html',context)

2) Open the booktest/urls.py file and configure the url.

    url(r'^html_escape/$', views.html_escape),

3) Create html_escape.html in the templates/booktest/directory.

<html>
<head>
    <title>Transferred meaning</title>
</head>
<body>
//Automatic escape: {{content}
</body>
</html>

4) Run the server and enter the following address in the browser.

http://127.0.0.1:8000/html_escape/

The escaped tag code will not be interpreted and executed directly, but will be presented directly to prevent the client from attacking the website by embedding js code.

The browsing effect is as follows:

Close escape

The filter escape can be used to escape the html of variables, and the default template can be escaped, which is generally omitted.

{{t1|escape}}

Filter safe: Disable escape and tell the template that this variable is safe and can explain execution.

{{data|safe}}

1) Modify the templates/booktest/html_escape.html code as follows.

<html>
<head>
    <title>Transferred meaning</title>
</head>
<body>
//Automatic escape: {{content}
<hr>
//Filter safe closes escape: {{content|safe}}
</body>
</html>

After refreshing the browser, the effect is as follows:

Label autoescape: Set a section of code to disable escape and accept on and off parameters.

{%autoescape off%}
...
{%endautoescape%}

1) Modify the templates/booktest/html_escape.html code as follows.

<html>
<head>
    <title>Transferred meaning</title>
</head>
<body>
Automatic escape:{{content}}
<hr>
Filter safe Turn off escape:{{content|safe}}
<hr>
Label autoescape Turn off escape:
{%autoescape off%}
{{content}}
{%endautoescape%}
</body>
</html>

After refreshing the browser, the effect is as follows:

string literal

For hard-coded html strings in templates, they are not escaped.

1) Modify the templates/booktest/html_escape.html code as follows:

<html>
<head>
    <title>Transferred meaning</title>
</head>
<body>
Automatic escape:{{content}}
<hr>
Filter safe Turn off escape:{{content|safe}}
<hr>
Label autoescape Turn off escape:
{%autoescape off%}
{{content}}
{%endautoescape%}
<hr>
Template hard coding does not escape:{{data|default:'<b>hello</b>'}}
</body>
</html>

2) After refreshing the browser, the effect is as follows:

If you want to escape, you need to manually code the escape.

1) Modify the templates/booktest/html_escape.html code as follows:

<html>
<head>
    <title>Transferred meaning</title>
</head>
<body>
Automatic escape:{{content}}
<hr>
Filter safe Turn off escape:{{content|safe}}
<hr>
Label autoescape Turn off escape:
{%autoescape off%}
{{content}}
{%endautoescape%}
<hr>
Template hard coding does not escape:{{data|default:'<b>hello</b>'}}
<hr>
Template hard-coded manual escape:{{data|default:"&lt;b&gt;123&lt;/b&gt;"}}
</body>
</html>

2) After refreshing the browser, the effect is as follows:

 

CSRF

CSRF is spelled Cross Site Request Forgery, translated as cross-station request forgery. CSRF means that an attacker steals your identity and sends malicious requests in your name. CSRF can do things like sending emails, sending messages, stealing your account, even buying goods, transferring virtual money in your name. Problems include personal privacy leaks and property security.

The CSRF schematic diagram is as follows:

If you want to prevent CSRF, first of all, the important information transmission is POST mode rather than GET mode. Next, the attack mode of POST request and the avoidance in Django are discussed.

Example

The operation of the attack process can be understood without repetition.

1) Open the booktest/views.py file and create the view login, login_check, post and post_action.

def login(reqeust):
    return render(reqeust, 'booktest/login.html')

def login_check(request):
    username = request.POST.get('username') #Get the username
    password = request.POST.get('password') #Get the password

    # check
    if username == 'smart' and password == '123':
        request.session['username']=name #Remember the login username
        request.session['islogin']=True #Determine whether the user is logged in
        return redirect('/post/')
    else:
        return redirect('/login/')

def post(request):
    return render(request, 'booktest/post.html')

def post_action(request):
    if request.session['islogin']:
        username = request.session['username']
        return HttpResponse('user'+username+'Send a post')
    else:
        return HttpResponse('Posting failure')

2) Open the booktest/urls.py file and configure the url.

url(r'^login/$', views.login),
url(r'^login_check/$', views.login_check),
url(r'^post/$', views.post),
url(r'^post_action/$',views.post_action),

3) Create login.html and post.html in the templates/booktest / directory.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Login case</title>
</head>
<body>
<form method="post" action="/login_check/">
    //User name: <input type="text" name="username"/><br/>
    //Password: <input type="password" name="password"/><br/>
    <input type="submit" value="Submission"/>
</form>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Poster Page</title>
</head>
<body>
<form method="post" action="/post_action/">
    //Title: <input type="text" name="title"/><br/>
    //Content: <textarea name="content"></textarea>
    <input type="submit" value="Posting"/>
</form>
</body>
</html>

4) Start the running server, using IP mode, because other IP requests are to be demonstrated.

python manage.py runserver 172.16.179.130:8000

5) Back to windows, enter the following address in the browser, and call this label Website A.

http://172.16.179.130:8000/login/

The browsing effect is as follows:

Enter the username and password, click login, the effect is as follows:

6) Using IIS server in windows to simulate another website, create post.html, copy template / booktest / post.html content, and modify action path.

<html>
<head>
    <title>Poster Page</title>
</head>
<body>
<form method="post" action="http://172.16.179.130:8000/post_action/">
  Title:<input type="text" name="title"/><br/>
  content:<textarea name="content"></textarea>
  <input type="submit" value="Posting"/>
</form>
</body>
</html>

7) In windows, the browser looks at the effect as follows, and calls this label Web Site B.

8) csrf protection is enabled by default in Django project. Now disable it. Open the test4/settings.py file and comment out the csrf middleware.

9) Click on the first label of the visitor, website A, and click the "Post" button, as follows:

10) Click on the second label of the visitor, IIS Website B, and click the "Post" button, as follows:

Comparing the two pictures above, it is found that the post_action view of website A can be accessed from both website A and website B, which is unsafe.

Preventing CSRF

1) Django provides CSRF middleware to prevent CSRF attacks, just need to enable CSRF Middleware in test4/settings.py.

2) Back to windows browser, click "Submit" button in website A and website B respectively. The effect is the same, as follows:

3) This is troublesome, because website A itself can not access, and then template / booktest / post. HTML content, in the form form using the label csrf_token.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Poster Page</title>
</head>
<body>
<form method="post" action="/post_action/">
    {% csrf_token %}
    //Title: <input type="text" name="title"/><br/>
    //Content: <textarea name="content"></textarea>
    <input type="submit" value="Posting"/>
</form>
</body>
</html>

4) Go back to the windows browser and click the "Submit" button in Web Site A. The effect is as follows:

5) Go back to windows browser and click the "Submit" button in Web Site B. The effect is as follows:

Well, CSRF protection has been successfully completed in Django.

summary

  • The above demonstration process can be understood without repetition. The following is the key point, which must be remembered.
  • Important information, such as amount, integral, etc., is transmitted by POST.
  • Enable CSRF middleware by default
  • Add the label csrf_token when post ing in the form

Protection Principle

After adding tags, you can look at the source code of post.html and find an additional hidden domain.

Understanding the principle is enough.

View cookie information in the browser's Developer Tools.

Description: When the middleware is enabled and the label csrf_token is added, a Cookie message will be written to the client browser. The value of this information is consistent with the value attribute of the hidden domain input element. When submitted to the server, it will be verified by the CSRF middleware first. If the comparison fails, it will return 403 pages instead of later. Continuous processing.

 

 

Verification Code

In user registration and login pages, in order to prevent violent requests, the authentication code function can be added. If the authentication code is wrong, it does not need to continue processing, which can alleviate the pressure of business servers and database servers.

Manual Implementation of Verification Code

The next code is not required to be written manually, because it can be found a lot on the Internet.

1) Installation package Pillow 3.4.1.

pip install Pillow==3.4.1

Click View PIL Module API Image, ImageDraw, ImageFont objects and methods are used in the following code.

2) Create the view verify_code in the booktest/views.py file.

  • Tip 1: Randomly generate strings and store them in session for subsequent judgment.
  • Tip 2: View returns mime-type as image/png.
from PIL import Image, ImageDraw, ImageFont
from django.utils.six import BytesIO
...
def verify_code(request):
    #Introducing Random Function Module
    import random
    #Define variables for background, width and height of the picture
    bgcolor = (random.randrange(20, 100), random.randrange(
        20, 100), 255)
    width = 100
    height = 25
    #Create screen objects
    im = Image.new('RGB', (width, height), bgcolor)
    #Create Brush Objects
    draw = ImageDraw.Draw(im)
    #Drawing Noise Points by Calling the point() Function of the Brush
    for i in range(0, 100):
        xy = (random.randrange(0, width), random.randrange(0, height))
        fill = (random.randrange(0, 255), 255, random.randrange(0, 255))
        draw.point(xy, fill=fill)
    #Define alternative values for validation codes
    str1 = 'ABCD123EFGHIJK456LMNOPQRS789TUVWXYZ0'
    #Random selection of four values as verification codes
    rand_str = ''
    for i in range(0, 4):
        rand_str += str1[random.randrange(0, len(str1))]
    #Construct font objects, and the font path of ubuntu is "/ usr/share/fonts/truetype/freefont"
    font = ImageFont.truetype('FreeMono.ttf', 23)
    #Construct font color
    fontcolor = (255, random.randrange(0, 255), random.randrange(0, 255))
    #Draw four words
    draw.text((5, 2), rand_str[0], font=font, fill=fontcolor)
    draw.text((25, 2), rand_str[1], font=font, fill=fontcolor)
    draw.text((50, 2), rand_str[2], font=font, fill=fontcolor)
    draw.text((75, 2), rand_str[3], font=font, fill=fontcolor)
    #Release the Brush
    del draw
    #Save session for further validation
    request.session['verifycode'] = rand_str
    #Memory file operation
    buf = BytesIO()
    #Save the picture in memory with the file type png
    im.save(buf, 'png')
    #Return image data in memory to client, MIME type is picture png
    return HttpResponse(buf.getvalue(), 'image/png')

3) Open the booktest/urls.py file and configure the url.

    url(r'^verify_code/$', views.verify_code),

4) Run the server and enter the following address in the browser.

http://127.0.0.1:8000/verify_code/

5) The browsing effect is as follows:

Can refresh several times to see if the value will change.

Call Verification Code

1) In the booktest/views.py file, create the view verify_show.

def verify_show(request):
    return render(request,'booktest/verify_show.html')

2) Open the booktest/urls.py file and configure the url.

    url(r'^verify_show/$', views.verify_show),

3) Create verify_show.html in the templates/booktest/directory.

<html>
<head>
    <title>Verification Code</title>
</head>
<body>
<form method="post" action="/verify_yz/">
    {%csrf_token%}
    <input type="text" name="yzm">
    <img id="yzm" src="/verify_code/"/>
    <span id="change">Can't see clearly, change one</span>
    <br>
    <input type="submit" value="Submission">
</form>
</body>
</html>

4) Run the server and enter the following address in the browser.

http://127.0.0.1:8000/verify_show/

5) The browsing effect is as follows:

Verification

1) In the booktest/views.py file, create the view verify_yz.

def verify_yz(request):
    yzm=request.POST.get('yzm')
    verifycode=request.session['verifycode']
    response=HttpResponse('no')
    if yzm==verifycode:
        response=HttpResponse('ok')
    return response

2) Open the booktest/urls.py file and configure the url.

    url(r'^verify_yz/$', views.verify_yz),

3) Refresh after returning to the browser, fill in the validation code in the text box, and click the submit button.

4) The browsing effect is as follows:

 

Reverse analysis

Let's see what we did first.

1) Open the booktest/views.py file and create views fan1 and fan2.

def fan1(request):
    return render(request,'booktest/fan1.html')
def fan2(request):
    return HttpResponse('fan2')

2) Open the booktest/urls.py file and configure the url.

    url(r'^fan1/$', views.fan1),
    url(r'^fan2/$', views.fan2),

3) Create fan1.html in the templates/booktest/directory.

<html>
<head>
    <title>Reverse analysis</title>
</head>
<body>
//Ordinary link: <a href="/fan2/">fan2</a>
</body>
</html>

4) Run the server and enter the following address in the browser:

http://127.0.0.1:8000/fan1/

The browsing effect is as follows:

5) Click on the link and turn to fan2. The effect is as follows:

6) Open the booktest/urls.py file and modify the regular expression of fan2 to fan_show.

    url(r'^fan_show/$', views.fan2),

7) Open the browser, step back, click the link again after refreshing, and browse the following picture:

The problem arises: with the increase of functions, more views will appear. Maybe the regular expressions that were configured before are inaccurate, so we need to modify the regular expressions. But once the regular expressions are modified, all the corresponding hyperlinks will be modified before. It's really a troublesome thing, and maybe some of them will be omitted. Hyperlinks forgot to be modified. Is there any way to dynamically generate links based on regular expressions? Answer: Reverse analysis.

Reverse parsing is used in two places: hyperlinks in templates and redirections in views.

Reverse analysis

To achieve the reverse parsing function, the following steps are needed:

1) Define namespace attributes for include in test4/urls.py.

    url(r'^',include('booktest.urls',namespace='booktest')),

2) Define the name attribute for url in booktest/urls.py and modify it to fan2.

    url(r'^fan2/$', views.fan2,name='fan2'),

3) Use url tags as hyperlinks in templates. Here is the template / booktest / fan1. HTML file.

<html>
<head>
    <title>Reverse analysis</title>
</head>
<body>
Ordinary links:<a href="/fan2/">fan2</a>
<hr>
Reverse analysis:<a href="{%url 'booktest:fan2'%}">fan2</a>
</body>
</html>

4) Back in the browser, back up, refresh, view the source file as shown below, the two link addresses are the same.

5) In booktest/urls.py, change fan2 to fan_show.

    url(r'^fan_show/$', views.fan2,name='fan2'),

6) Go back to the browser, refresh and view the source file as shown below. The two link addresses are different.

7) Reverse parsing can also be used in view reorientation.

from django.shortcuts import redirect
from django.core.urlresolvers import reverse

return redirect(reverse('booktest:fan2'))

Summary: When defining url, we need to define namespace attribute for inclusion, name attribute for url, use URL tag in template, use reverse function in view, generate address dynamically according to regular expression, and reduce maintenance cost in later period.

Parameters of the URL

Some url configurations have parameters in their regular expressions. Next, we will explain how to pass parameters.

Case 1: Position parameters

1) In booktest/urls.py, modify fan2 as follows:

    url(r'^fan(\d+)_(\d+)/$', views.fan3,name='fan2'),

2) In booktest/views, define view fan3 as follows:

def fan3(request, a, b):
    return HttpResponse(a+b)

3) Modify the templates/booktest/fan1.html file as follows:

<html>
<head>
    <title>Reverse analysis</title>
</head>
<body>
Ordinary links:<a href="/fan2_3/">fan2</a>
<hr>
Reverse analysis:<a href="{%url 'booktest:fan2' 2 3%}">fan2</a>
</body>
</html>

4) Go back to the browser, refresh and view the source file as follows:

The format of the position parameter is passed by redirection as follows:

return redirect(reverse('booktest:fan2', args=(2,3)))

Case 2: Keyword parameters

1) In booktest/urls.py, modify fan2 as follows:

    url(r'^fan(?P<id>\d+)_(?P<age>\d+)/$', views.fan4,name='fan2'),

2) In booktest/views, define view fan4 as follows:

def fan4(request, id, age):
    return HttpResponse(id+age)

2) Modify the templates/booktest/fan1.html file as follows:

<html>
<head>
    <title>Reverse analysis</title>
</head>
<body>
Ordinary links:<a href="/fan100_18/">fan2</a>
<hr>
Reverse analysis:<a href="{%url 'booktest:fan2' id=100 age=18%}">fan2</a>
</body>
</html>

3) Go back to the browser, refresh and view the source file as follows:

Passing keyword parameter formats using redirection are as follows:

return redirect(reverse('booktest:fan2', kwargs={'id':100,'age':18}))

 

summary

  • Template grammar
    • variable
    • Label
    • Filter
    • Notes
  • Template Inheritance
  • html escape
  • CSRF
  • Verification Code
  • Reverse analysis

task

  • Skillfully complete the day code
  • Realize the function of "cannot see clearly, change one"
  • Learn to use third-party authentication codes

 

Change another one

  • Click "Can't see clearly, change one" and replace it with a new verification code.
<script type="text/javascript" src="/static/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
    $(function(){
        $('#change').css('cursor','pointer').click(function() {
            $('#yzm').attr('src',$('#yzm').attr('src')+1)
        });
    });
</script>
...
<img id="yzm" src="/verify_code/?1"/>
<span id="change">Can't see clearly, change one</span>

 

Tags: Django Session Attribute Windows

Posted on Tue, 13 Aug 2019 02:32:00 -0700 by Jamesm