html automatic conversion method for templates in django

  • 2020-09-16 07:34:46
  • OfStack

1. Source of demand:

If the user fills in 1 paragraph in the text box < script > alert(xxx); < /script > The next time the template loads the data, display this code in the browser, and a warning box will pop up. Therefore, this is one way to attack XSS (cross-domain scripting), and we certainly cannot allow this to happen, so django has enabled automatic switching by default. Turn this code into plain text for display.

2. How to close:

You have to ask why do you need to close the XSS vulnerability when automatic switching can close it? The reason is simple: if you have a trusted piece of HTML code in your database, you want to insert it into your page document, and you don't want to be treated as a string. At this point, you can turn off certain modules. django provides two ways to do this:

For individual variables, use the safe filter to turn off the autotransform for individual variables, such as:


 this data Will be transferred: {{ data }}
 this data Will not be turned: {{ data|safe }}

For the template block, autoescape can be used to unify 1 management. It has two parameters, off and on, which are used to close and open automatic transformation respectively. For example, the following code can close the automatic transformation of 1 whole code:


{% autoescape off %}
 name: {{ name }}
 age: {{ age }}
{% endautoescape %}

The following code first turns off the automatic conversion and then turns on the automatic conversion function:


Auto-escaping is on by default. Hello {{ name }}
{% autoescape off %}
 This will not be auto-escaped: {{ data }}.
 Nor this: {{ other_data }}
 {% autoescape on %}
  Auto-escaping applies again: {{ name }}
 {% endautoescape %}
{% endautoescape %}

Note: The scope of the autoescape tag can affect not only the current template but also other templates through the include tag and the block tag. Remember this 1!

3: Automatic translation of string constants in filter parameters:


{{ data|default:"no data" }}

Analyzing the above code, the view function displays data if it provides data data, or no data by default if it does not. If you want to show with/by default, < ,",', & It's not going to switch, so if you want to show 3 < 1 Such special characters will have a structural effect on the html document. But you can pass 3 & lt; 1 In this way, transfer output is carried out.


Related articles: