Template
Overview
As a web framework, Django provides templates for writing HTML code, as well as embedding template code to complete page development faster and more easily, and then returning the resulting HTML string to the client browser by rendering the template in the view. Templates are dedicated to expressing appearances, not program logic. The template design enables the separation of the business logic view from the display content template, one view can use either template, and one template can be used by multiple views.
Create a template folder
- Define a Templates folder in the project's file
- Create a folder in the created folder for each app's HTML folder named and the name of the application with the same name
- Go to setting.py Add configuration file path find templates entry
The template contains two parts:
- Static part, including HTML, CSS, JS.
- The dynamic part is the template language.
The Django processing template is divided into two phases:
- 1. Load: Find the template file based on the given path and put it in memory after compiling.
- 2. Rendering: Interpolates the template using contextual data and returns the resulting string.
The process of template loading
From django.template Import loader, requestcontextdef index (Request): "" "" "" "" " # 1. Load template file, get a template object temp = Loader.get_template (' booktest/index.html ') # 2. Defining template contexts to pass data to a template context = RequestContext (request, {' Kay ': ' KK ') }) # 3. HTML content that produces a raw standard res_html = Temp.render (context) # 4. Return content to the browser return HttpResponse (res_html) --Shorthand return render (Request, ' booktest/index.html ', {' Kay ': ' Kaykay '})
Template language
Variable
Format:
- {{Template variable name}}
The template variable name is composed of numbers, letters, underscores, and dots, and cannot begin with an underscore.
Parse order for template variables:
Example: Book.title
- Treat book as a dictionary, take title as key, value book[' title ']
- The book as an object, the title as a property, value Book.title
- Treat book as an object, take title as the method name, and value Book.title ()
Example: book.0
- Think of book as a dictionary, take 0 as key, value book[' 0 ']
- Think of book as a list, take 0 as subscript, value book[0]
Note: If parsing fails, the template variable is populated with an empty string when the content is generated.
Label
The syntax is as follows:
{% code snippet%}
The for tag syntax is as follows:
{%for item in list%} The loop logic {{Forloop.counter}} indicates that the current is the number of loops, starting from 1 {%empty%} The list is empty or does not exist when you execute this logic {%endfor%}
The IF tag syntax is as follows:
{%if ...%} logical 1{%elif ...%} logical 2{%else%} logic 3{%endif%}
Relational comparison operators:
> < >= <= = = =!
Note: For comparison operations, there must be spaces on both sides of the comparison operator.
Logical comparison:
Not and OR
Example:
{% for book in books%} {% if book.id < 3} <li class= "Red" >{{book.btitle}}</li> {% elif book.id = 3} <li class= "Gold" >{{book.btitle }}</li> {% elif book.id > 3} <li class= "green" >{{book.btitle}}</li> {% endif%}{% en Dfor%}{% in Books2%}{% empty%} <li> meteor butterfly Sword </li>% endfor%}
Filter filters
- Use the pipe symbol | To apply a filter for calculations, conversion operations, which can be used in variables, tags.
- If the filter requires parameters, use a colon: pass the parameter.
- Filters are used to manipulate template variables
Grammar:
- Variables | filters: Parameters
Internal Filter Parameters
- Date: Changes the display format of the dates.
- Y represents the year, the format is 4 bits, and Y represents the year of two bits.
- M represents the month, the format is 01,02,12 and so on.
- J represents the day, the format is.
- H represents the time when 24 is binary, H is 12 binary.
- I represents the minute, which is 0-59.
- s represents seconds, which is 0-59.
- Example:
- Value|date: "Y year M Moon J Day H I min s second"
- Lengths: Length, return string contains the number of characters, list, tuple, dictionary number of elements.
- defaults to default, and returns a default value if the variable does not exist.
- Data|default: ' Default value '
More built-in filters. Http://python.usyiyi.cn/translate/django_182/ref/templates/builtins.html
Example:
{% for book in books%} {% if book.btitle|length < 5} <li>{{book.btitle}}--{{book.bpub_date|date: ' Y year-M month-j Day '}}</li> {% Else%} <li>{{ Book.btitle}}--{{book.bpub_date}}</li> {% endif%}{% endfor%}{# Set a default value when using a non-existent template variable #}{{date|default: "Hello " }}
Custom Filter Flow
- Create a Templatetags package in the app's directory
- . Define the filter.py file in the package
Example:
# coding=utf-8# introduced registration object from django.template import libraryregister=library () # using adorners to register @register.filter# define the redundancy function mod, Add value to 2 remainder def mod (num): return num%2 = = 0# filter with parameters @register.filterdef mod (num, val): return num%val = = 0
3. Import in HTML file (same as built-in filter usage)
{%load filters%} {% if book.id|mod%} <li class= "Red" >{{Book.btitle}}---{{book.bpub_date|date: ' y-m-j '}}</li>{% else%} <li class= " Green ">{{Book.btitle}}---{{book.bpub_date|date: ' Y year-M month-j Day '}}</li>{% endif%}
Use with parameters
{% if book.id|mod:3%}<li class= "Red" >{{Book.btitle}}---{{book.bpub_date|date: ' y-m-j '}}</li>{% else%}< C0/><li class= "green" >{{Book.btitle}}---{{book.bpub_date|date: ' Y year-M month-j Day '}}</li>{% endif%}
Comments
Use the following template comments in the template, this code will not be compiled, not output to the client; HTML annotations can only comment on HTML content and cannot comment on the template language.
Single-line Comment:
{# comment Content #}
Multi-line Comments:
{% Comment%} comment Contents {% endcomment%}
Template inheritance
Overview:
Template inheritance and class inheritance mean the same thing, mainly to improve code reuse and reduce the workload of developers. Typical application: The head and tail information of the website.
In the parent template you can define blocks, using tags:
{% blocks block name%} block Middle can write content, can also not write {% Endblock block name%}
After a child template is inherited from a parent template, you can override the contents of a piece of the parent template.
Inheritance format:
{% extends parent template file path%} {% block name%} {{Block.super}} #获取父模板中块的默认内容
Rewritten content
{% Endblock block name%}
Example Parent Template
<! DOCTYPE html>
Sample Template
{% extends ' booktest/base.html '%} {% block B1%} {{Block.super}}
Summary : Write different content in the block, the same content written on the outside of the block, the same content will be the quilt template inheritance
Ajax
In the case of not all of the page is loaded, the page is refreshed
Ajax case in HTML
Get mode:
{# Username,password data in a user-submitted form #}
$.get ('/login_ajax_check/?username= ' +username+ "&password=" +password, function (data) { if (data.res = = ' OK ') {
{# Data passed to the view parameter #} Location.href = '/success/'
{# location.href let the browser Access Success page #} } lse{ $ (' #errinfo '). html (' User name or password error '). Show () })
Post mode:
{# Username,password data in a user-submitted form #}
$.post ('/login_ajax_check/', {' username ': username, ' Password ': password}, function (data) {alert (data.res)})
CsrfCSRF is fully spelled as cross site request forgery, which is translated as a multi-site solicitation forgery. CSRF refers to an attacker who steals your identity and sends a malicious request in your name. The things that CSRF can do include: Send mail in your name, message, steal your account, even buy goods, virtual money transfer ... Issues include: personal privacy breaches and property security.
Why cross-site request forgery occurs :
1 browsers access 2 different sites, A, b
2. The browser login A website successfully will be logged in the status of the session to save the next time the browser to display a successful login page, do not need to log in because the browser will save the session status information with the past verification, through the need not display the login page
3. Now use the same browser to access the B site, and then submit the data to a site, at this time because the same browser, the previously generated session data will be submitted to the a site, the previous saved session information will be submitted to a site, with authentication, The case of cross-site request forgery is generated.
Workaround:
- Important information such as amount, points, etc., by post mode
- Enable CSRF middleware, default enable "Settings in project configuration Files"
- ' Django.middleware.csrf.CsrfViewMiddleware ', CSRF middleware configuration--enabled by default
- Add a label to the form form Csrf_token "{% Csrf_token%}"
Description :
when middleware is enabled and tagged Csrf_token is added, a cookie is written to the client browser, which is consistent with the Value property of the hidden domain control, which is validated by the CSRF middleware before being submitted to the server and returned to page 403 if the comparison fails. , and no subsequent processing is performed .
Reverse parsing
The problem arises:
As the function increases, there will be more views, perhaps the regular expression before the configuration is not accurate enough, so it is necessary to modify the regular expression, but once the regular expression has been modified, all the corresponding hyperlinks have to be modified, it is a troublesome thing, and may also miss some hyperlinks forget to modify, Is there a way to dynamically generate links based on regular expressions?
Answer: Reverse parsing .
Description: Reverse parsing changes the URL of the corresponding HTML submission based on the URL matching changes in the app.
Use process:
Inverse resolution with no parameters
1. Write in the project's url.py file
URL (r ' ^ ', include (' Booktest.urls ', namespace= "Booktest"))
2. Write to the URL of the app
URL (r ' ^fan6/$ ', views.fan1, name= ' fan2 '),
3. Write to the corresponding HTML file:
<a href= "{% url ' booktest:fan2 '%}" > Reverse resolution </a>
Inverse resolution of positional parameters
2. Write to the URL of the app
URL (r ' ^delete_ (\d+) _ (\d+)/$ ', Views.reverse_url_need_args, name= ' delete '), #带参数的反向解析
3. Write to the corresponding HTML file:
<a href= "{% url ' booktest:delete ' 3 4}" > Reverse resolution with Parameters </a><br>
Inverse parsing of keyword parameters
2. Write to the URL of the app
URL (r ' ^delete_ (? p<p1>\d+) _ (? p<p2>\d+)/$ ', Views.reverse_url_need_args, name= ' Delete2 '), #带关键字参数的反向解析
3. Write to the corresponding HTML file:
<a href= "{% url ' booktest:delete2 ' p1=33 p2=44%}" > keyword parameter reverse resolution </a>
Use reverse parsing when redirecting
Import: from django.core.urlresolvers import reverse
With no parameters
Return Redirect (reverse (' booktest:fan2 '))
Position parameters
Return Redirect (reverse (' Booktest:delete ', args= (33, 44)))
Keyword parameters
Return Redirect (reverse (' booktest:delete2 ', kwargs={' P1 ': +, ' P2 ': 33}))
Django Template Summary [Template language, template inheritance, csrf attack, reverse parsing]