Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Django template

Django template

Django's template system (Template System) is a core component used to separate business logic (Python) from the presentation layer (HTML); it allows developers to dynamically generate HTML pages through simple tags and variables.

In the previous chapter we used django.http.HttpResponse() to output "Hello World!", which mixes data with views and does not conform to Django's MVT philosophy.

In this chapter we will introduce the application of Django templates in detail. A template is a text used to separate the presentation form and content of a document.

Function Syntax/Example Applicable scenarios
Variable rendering {{ variable }} Dynamically display data
Logic control {% if %}, {% for %} Conditional/loop rendering
Template inheritance {% extends %}, {% block %} Avoid repetitive HTML structure
Static files {% static 'path' %} Load CSS/JS/images
Custom filters @register.filter Extend template functionality

Template Application Examples

Continuing from the previous chapter's project, we will create a templates directory under the HelloWorld directory and create a runoob.html file; the whole directory structure is as follows:



HelloWorld/

|-- HelloWorld

|   |-- __init__.py

|   |-- __init__.pyc

|   |-- settings.py

|   |-- settings.pyc

|   |-- urls.py

|   |-- urls.pyc

|   |-- views.py

|   |-- views.pyc

|   |-- wsgi.py

|   `-- wsgi.pyc

|-- manage.py

`-- templates

    `-- runoob.html

The runoob.html file code is as follows:

HelloWorld/templates/runoob.html file code:

<

h1

{{ hello }}

h1

From the template we know that variables use double braces {{ }}.

Next we need to tell Django the path of the template file; open the HelloWorld/HelloWorld/settings.py file and modify TEMPLATES the DIRS in it to [BASE_DIR / "templates"], as follows:

HelloWorld/HelloWorld/settings.py file code:

...

TEMPLATES

=

[

   

{

       

'BACKEND'

:

'django.template.backends.django.DjangoTemplates'

,

       

'DIRS'

:

[

BASE_DIR /

"templates"

]

,

     

Modification location

       

'APP_DIRS'

:

True

,

       

'OPTIONS'

:

{

           

'context_processors'

:

[

               

'django.template.context_processors.debug'

,

               

'django.template.context_processors.request'

,

               

'django.contrib.auth.context_processors.auth'

,

               

'django.contrib.messages.context_processors.messages'

,

           

]

,

       

}

,

   

}

,

]

...

We now modify views.py and add a new object to submit data to the template:

HelloWorld/HelloWorld/views.py file code:

from

django

.

shortcuts

import

render

def

runoob

(

request

)

:

context

= {}

context

[

'

hello

'

]

=

'

Hello World!

'

return

render

(

request

,

'

runoob.html

'

,

context

)

As you can see, here we use render to replace the previously used HttpResponse; render also uses a dictionary context as a parameter.

The key-value of elements in the context dictionary hello corresponds to the variable {{ hello }} in the template.

HelloWorld/HelloWorld/urls.py file code:

from

django

.

contrib

import

admin

from

django

.

urls

import

path

from

.

import

views

urlpatterns

=

[

path

(

'

admin/

'

,

admin

.

site

.

urls

)

,

path

(

'

runoob/

'

,

views

.

runoob

)

,

]

Next, we enter the HelloWorld directory and enter the following command to start the server:



python3 manage.py runserver 0.0.0.0:8000

Visit again http://127.0.0.1:8000/runoob, you can see the page:

In this way we have completed using a template to output data, thereby achieving separation of data and views.

Next we will introduce in detail the commonly used syntax rules in templates.


Django Template Tags

Syntax:

{% tag %}

Control template logic; commonly used tags:

tag Purpose
{% for %} Loop through lists/dictionaries
{% if %} Conditional Judgment
{% extends %} Inherit a base template
{% block %} Define a content block that can be overridden by child templates
{% include %} Embed other template fragments
{% url %} Reverse-resolve URLs (avoid hard-coded paths)
{% csrf_token %} Generate a CSRF token (for POST forms)

Variables

Template syntax:

view:{"HTML变量名" : "views变量名"}

HTML:{{变量名}}

HelloWorld/HelloWorld/views.py file code:

from

django.

shortcuts

import

render

def

runoob

(

request

)

:

  views_name

=

"Runoob Tutorial"

 

return

 render

(

request

,

"runoob.html"

,

{

"name"

:views_name

}

)

runoob.html in templates:

{{ name }}

Visit http://127.0.0.1:8000/runoob again, and you can see the page:

List

In runoob.html in templates, you can use the . index subscript to retrieve the corresponding element.

HelloWorld/HelloWorld/views.py file code:

from

django.

shortcuts

import

render

def

runoob

(

request

)

:

    views_list

=

[

"Runoob Tutorial1"

,

"Runoob Tutorial2"

,

"Runoob Tutorial3"

]

   

return

render

(

request

,

"runoob.html"

,

{

"views_list"

: views_list

}

)

HelloWorld/templates/runoob.html file code:

<

p

{{ views_list }}

p

Retrieve the entire list

<

p

{{ views_list.0 }}

p

Retrieve the first element of the list

Visit http://127.0.0.1:8000/runoob again, and you can see the page:

Dictionaries

In runoob.html in templates, you can use .key to retrieve the corresponding value.

HelloWorld/HelloWorld/views.py file code:

from

django.

shortcuts

import

render

def

runoob

(

request

)

:

    views_dict

=

{

"name"

:

"Runoob Tutorial"

}

   

return

render

(

request

,

"runoob.html"

,

{

"views_dict"

: views_dict

}

)

HelloWorld/templates/runoob.html file code:

<

p

{{ views_dict }}

p

<

p

{{ views_dict.name }}

p

Visit http://127.0.0.1:8000/runoob again, and you can see the page:

Filter

Template syntax:



{{ 变量名 | 过滤器:可选参数 }}

Template filters can modify a variable before it is displayed; filters use the pipe character, as follows:



{{ name|lower }}

After the {{ name }} variable is processed by the lower filter, uppercase text in the document is converted to lowercase.

Filter pipelines can be * chained *; that is, the output of one filter pipeline can serve as the input of the next pipeline:



{{ my_list|first|upper }}

The above example takes the first element and converts it to uppercase.

Some filters have parameters. A filter's parameter follows the colon and is always enclosed in double quotes. For example:



{{ bio|truncatewords:"30" }}

This will display the first 30 words of the variable bio.

Other filters:

default

default provides a default value for a variable.

If the boolean value of the variable passed by views is false, the specified default value is used.

The following values are false:



0  0.0  False  0j  ""  []  ()  set()  {}  None

HelloWorld/HelloWorld/views.py file code:

from

django.

shortcuts

import

render

def

runoob

(

request

)

:

    name

=

0

   

return

render

(

request

,

"runoob.html"

,

{

"name"

: name

}

)

HelloWorld/templates/runoob.html file code:

{{ name|default:"Runoob Tutorial666" }}

Visit http://127.0.0.1:8000/runoob again, and you can see the page:

length

Return the length of an object; applicable to strings and lists.

A dictionary returns the number of key-value pairs; a set returns the length after deduplication.

HelloWorld/HelloWorld/views.py file code:

from

django.

shortcuts

import

render

def

runoob

(

request

)

:

    name

=

"Runoob Tutorial"

   

return

render

(

request

,

"runoob.html"

,

{

"name"

: name

}

)

HelloWorld/templates/runoob.html file code:

{{ name|length}}

Visit http://127.0.0.1:8000/runoob again, and you can see the page:

filesizeformat

Display file sizes in a more readable way (i.e., '13 KB', '4.1 MB', '102 bytes', etc.).

A dictionary returns the number of key-value pairs; a set returns the length after deduplication.

HelloWorld/HelloWorld/views.py file code:

from

django.

shortcuts

import

render

def

runoob

(

request

)

:

    num

=

1024

   

return

render

(

request

,

"runoob.html"

,

{

"num"

: num

}

)

HelloWorld/templates/runoob.html file code:

{{ num|filesizeformat}}

Visit http://127.0.0.1:8000/runoob again, and you can see the page:

date

Format a date variable according to a given format.

The format Y-m-d H:i:s returns year-month-day hour:minute:second in the format of time.

HelloWorld/HelloWorld/views.py file code:

from

django.

shortcuts

import

render

def

runoob

(

request

)

:

   

import

datetime

    now  

=

datetime

.

datetime

.

now

(

)

   

return

render

(

request

,

"runoob.html"

,

{

"time"

: now

}

)

HelloWorld/templates/runoob.html file code:

{{ time|date:"Y-m-d" }}

Visit http://127.0.0.1:8000/runoob again, and you can see the page:

truncatechars

If the total number of characters in a string exceeds the specified number of characters, the part after it will be truncated.

The truncated string will end with ...

HelloWorld/HelloWorld/views.py file code:

from

django.

shortcuts

import

render

def

runoob

(

request

)

:

    views_str

=

"Runoob Tutorial"

   

return

render

(

request

,

"runoob.html"

,

{

"views_str"

: views_str

}

)

HelloWorld/templates/runoob.html file code:

{{ views_str|truncatechars:2}}

Visit http://127.0.0.1:8000/runoob again, and you can see the page:

**safe **

Mark a string as safe, no escaping needed.

Only use safe when you can guarantee that the data passed from views.py is absolutely safe.

It has the same effect as mark_safe in the back-end views.py.

Django automatically escapes tag syntax passed from views.py into HTML files, making its semantics invalid. Adding the safe filter tells Django that the data is safe and need not be escaped, allowing the data's semantics to take effect.

HelloWorld/HelloWorld/views.py file code:

from

django.

shortcuts

import

render

def

runoob

(

request

)

:

    views_str

=

"Click to jump"

   

return

render

(

request

,

"runoob.html"

,

{

"views_str"

: views_str

}

)

HelloWorld/templates/runoob.html file code:

{{ views_str|safe }}

Visit http://127.0.0.1:8000/runoob again, and you can see the page:

if/else tags

The basic syntax format is as follows:



{% if condition %}

     ... display

{% endif %}

or:



{% if condition1 %}

   ... display 1

{% elif condition2 %}

   ... display 2

{% else %}

   ... display 3

{% endif %}

Determine whether to output based on a condition. if/else supports nesting.

The {% if %} tag accepts the and, or, or not keywords to judge multiple variables, or to negate a variable (not), for example:



{% if athlete_list and coach_list %}

     athletes 和 coaches 变量都是可用的。

{% endif %}

HelloWorld/HelloWorld/views.py file code:

from

django.

shortcuts

import

render

def

runoob

(

request

)

:

    views_num

=

88

   

return

render

(

request

,

"runoob.html"

,

{

"num"

: views_num

}

)

HelloWorld/templates/runoob.html file code:

{%

if

num

90

and

num

<=

100

%} excellent {%

elif

num

60

and

num

<=

90

%} pass {%

else

%} go play elsewhere~ {%

endif

%}

Visit http://127.0.0.1:8000/runoob again, and you can see the page:

for tag

{% for %} allows us to iterate over a sequence.

Similar to Python's for statement, the loop syntax is for X in Y, where Y is the sequence to iterate and X is the variable name used in each particular loop.

In each loop, the template system renders all content between {% for %} and {% endfor %}.

For example, given an athlete list variable athlete_list, we can use the following code to display this list:



    {% for athlete in athlete_list %}
  • {{ athlete.name }}
  • {% endfor %}

HelloWorld/HelloWorld/views.py file code:

from

django.

shortcuts

import

render

def

runoob

(

request

)

:

    views_list

=

[

"Runoob Tutorial"

,

"Runoob Tutorial1"

,

"Runoob Tutorial2"

,

"Runoob Tutorial3"

,

]

   

return

render

(

request

,

"runoob.html"

,

{

"views_list"

: views_list

}

)

HelloWorld/templates/runoob.html file code:

{% for i in views_list %} {{ i }} {% endfor %}

Visit http://127.0.0.1:8000/runoob again, and you can see the page:

Add a reversed to the tag so that the list is iterated in reverse:



{% for athlete in athlete_list reversed %}

...

{% endfor %}

HelloWorld/templates/runoob.html file code:

{% for i in views_list reversed%} {{ i }} {% endfor %}

Visit http://127.0.0.1:8000/runoob again, and you can see the page:

Iterate over a dictionary: you can use a dictionary directly .items method, using variable unpacking to get keys and values separately.

HelloWorld/HelloWorld/views.py file code:

from

django.

shortcuts

import

render

def

runoob

(

request

)

:

    views_dict

=

{

"name"

:

"Runoob Tutorial"

,

"age"

:

18

}

   

return

render

(

request

,

"runoob.html"

,

{

"views_dict"

: views_dict

}

)

HelloWorld/templates/runoob.html file code:

{% for i,j in views_dict.items %} {{ i }}---{{ j }} {% endfor %}

Visit http://127.0.0.1:8000/runoob again, and you can see the page:

Inside the {% for %} tag, you can get the loop sequence number through the {{forloop}} variable.

HelloWorld/HelloWorld/views.py file code:

from

django.

shortcuts

import

render

def

runoob

(

request

)

:

     views_list

=

[

"a"

,

"b"

,

"c"

,

"d"

,

"e"

]

     

return

render

(

request

,

"runoob.html"

,

{

"listvar"

: views_list

}

)

HelloWorld/templates/runoob.html file code:

{% for i in listvar %} {{ forloop.counter }} {{ forloop.counter0 }} {{ forloop.revcounter }} {{ forloop.revcounter0 }} {{ forloop.first }} {{ forloop.last }} {% endfor %}

Visit http://127.0.0.1:8000/runoob again, and you can see the page:

{% empty %}

Optional {% empty %} clause: executed when the loop is empty (i.e., the value after in is False).

HelloWorld/HelloWorld/views.py file code:

from

django.

shortcuts

import

render

def

runoob

(

request

)

:

  views_list

=

[

]

 

return

render

(

request

,

"runoob.html"

,

{

"listvar"

: views_list

}

)

HelloWorld/templates/runoob.html file code:

{% for i in listvar %} {{ forloop.counter0 }} {% empty %} Nothing here~ {% endfor %}

Visit http://127.0.0.1:8000/runoob again, and you can see the page:

You can nest {% for %} tags:



{% for athlete in athlete_list %}

    

{{ athlete.name }}

    {% for sport in athlete.sports_played %}
  • {{ sport }}
  • {% endfor %}
{% endfor %}

The comment tag

Django comments use {# #}.



{# 这是一个注释 #}

The include tag

The {% include %} tag allows including the content of other templates in a template.

The following example includes the nav.html template:



{% include "nav.html" %}


csrf_token

csrf_token is used in form forms and provides cross-site request forgery protection.

If you don't use {% csrf_token %} the tag, when using a form, redirecting to a page again will produce a 403 permission error.

Using the **{% csrf_token %}** tag, data submitted from a form will succeed.

Analysis:

First, send a request to the server to get the login page; at this time, the csrf middleware automatically generates a hidden input tag, in which the value attribute is a random string; when the user gets the login page, they also get this hidden input tag.

Then, when the user needs to submit data with a form, this input tag is submitted along with it to the csrf middleware, because a form submission includes all input tags; when the csrf middleware receives the data, it checks whether this random string is the one it first sent to the user; if so, the submission succeeds, otherwise, a 403 permission error is returned.


Custom tags and filters

1. Create a directory under the app directory templatetags (at the same level as the templates directory; the directory name can only be templatetags).



HelloWorld/

|-- HelloWorld

|   |-- __init__.py

|   |-- __init__.pyc

|   |-- settings.py

...

|-- manage.py

`-- templatetags

`-- templates

2. Create any py file under the templatetags directory, e.g.:my_tags.py。

3. The code of the my_tags.py file is as follows:

from django import template



register = template.Library()   #register的名字是固定的,不可改变

Modify the TEMPLATES option configuration in the settings.py file, adding the libraries configuration:

settings.py configuration file

...

TEMPLATES

=

[

   

{

       

'BACKEND'

:

'django.template.backends.django.DjangoTemplates'

,

       

'DIRS'

:

[

BASE_DIR

,

"/templates"

,

]

,

       

'APP_DIRS'

:

True

,

       

'OPTIONS'

:

{

           

'context_processors'

:

[

               

'django.template.context_processors.debug'

,

               

'django.template.context_processors.request'

,

               

'django.contrib.auth.context_processors.auth'

,

               

'django.contrib.messages.context_processors.messages'

,

           

]

,

           

"libraries"

:

{

                         

Add these three lines of configuration here

               

'my_tags'

:

'templatetags.my_tags'

 

Add these three lines of configuration here        

           

}

                                     

Add these three lines of configuration here

       

}

,

   

}

,

]

...

4. Use the decorator @register.filter to customize a filter.

**Note:** a decorator can have at most 2 parameters.

@register.filter

def my_filter(v1, v2):

    return v1 * v2

5. Use the decorator @register.simple_tag to customize a tag.

@register.simple_tag

def my_tag1(v1, v2, v3):

    return v1 * v2 * v3

6. Before using custom tags and filters, import the py file at the very top of the body in the html file.

{% load my_tags %}

7. Use custom filters in HTML.

{{ 11|my_filter:22 }}

8. Use custom tags in HTML.

{% my_tag1 11 22 33 %}

9. Semantic tags

Import mark_safe in the py file.



from django.utils.safestring import mark_safe

When defining a tag, use the mark_safe method to make the tag semantic, equivalent to the html() method in jQuery.

Same as the safe filter in front-end HTML files.

@register.simple_tag

def my_html(v1, v2):

    temp_html = "" %(v1, v2)

    return mark_safe(temp_html)

Use this custom tag in HTML to dynamically create tags in the page.

{% my_html "zzz" "xxx" %}


Configure static files

1. Create a statics directory in the project root directory.

2. Add the following configuration at the bottom of the settings file:



STATIC_URL = '/static/' # 别名 

STATICFILES_DIRS = [ 

    os.path.join(BASE_DIR, "statics"), 

]

3. Under the statics directory, create css, js, images, and plugins directories, to hold css files, js files, images, and plugins respectively.

4. Put the bootstrap framework into the plugins directory.

5. Include bootstrap in the head tag of the HTML file.

**Note:** the reference path should use the alias static from the configuration file, not the directory statics.



To use it in a template, you need to add {% load static %} code; in the following example we include an image from the static directory.

HelloWorld/HelloWorld/views.py file code:

from

django.

shortcuts

import

render

def

runoob

(

request

)

:

    name

=

"Runoob Tutorial"

   

return

render

(

request

,

"runoob.html"

,

{

"name"

: name

}

)

HelloWorld/templates/runoob.html file code:

{% load static %} {{name}}

<img src=">

{% static 'images/runoob-logo.png' %}

"

alt

=

"

runoob-logo

"

Visit http://127.0.0.1:8000/runoob again, and you can see the page:


Template inheritance

Templates can be reused through inheritance, reducing redundant content.

The header and footer content of web pages are generally the same, so we can achieve reuse through template inheritance.

The parent template holds reusable content; the child template inherits the parent template's content and places its own content.

Parent template

The block...endblock tag: A reserved area in the parent template, left for the child template to fill with differing content; different reserved areas cannot have the same name.

{% block 名称 %} 

预留给子模板的区域,可以设置设置默认内容

{% endblock 名称 %}

Child template

The child template uses the extends tag to inherit the parent template:

{% extends "父模板路径"%} 

If the child template does not set the content of a reserved area of the parent template, the default content set in the parent template is used; of course, you can also set none, leaving it empty.

The child template sets the content of a parent template's reserved area:



{ % block 名称 % }

内容 

{% endblock 名称 %}

Next, we first add a base.html file to the templates directory of the previous project, with the following code:

HelloWorld/templates/base.html file code:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>

Runoob Tutorial(runoob.com)

title

head

<

body

<

h1

Hello World!

h1

<

p

Runoob Tutorial Django test.

p

{% block mainbody %}

<

p

original

p

{% endblock %}

body

html

In the above code, the block tag named mainbody is the part that can be replaced by inheritors.

All {% block %} tags tell the template engine that child templates can override these parts.

runoob.html inherits base.html and replaces specific blocks; the modified code of runoob.html is as follows:

HelloWorld/templates/runoob.html file code:

{%

extends

"

base.html

"

%} {%

block

mainbody

%} <

p

inherits all the logic of

base

.

html

file

p

{%

endblock

%}

The first line of code shows that runoob.html inherits the base.html file. As you can see, block tags with the same name here are used to replace the corresponding blocks in base.html.

Visit the address http://127.0.0.1:8000/runoob again, and the output is as follows: