django prints an instance of html content

  • 2020-09-16 07:35:29
  • OfStack

Recently, I have been learning django, so I used django to make a simple website for practice. The specific function is to grab data from the Internet and put it on my website. However, I encountered a problem that django could not output the content in html format, but could only output it in the form of a string:


data = '<h1>hello world</h1>'
<p>{{ data }}</p>

What we aim to export is:


hello world

But the output is:


<h1>hello world</h1>

After searching the Internet for a long time, I finally found a solution:

Use django's filter for a single variable and tell Django that the string is not HTML escaped as follows:


data | safe

Use the autoescape tag for 1-paragraph template content, such as:


{% autoescape off %}
 {{ data }}
{% endautoescape %}

off means to turn off the escape of html, while replacing off with on means to escape html and html by default

Note: autoescape is inheritable, and if it is defined in the parent template, it also exists in the content section of the child template

We might wonder why django escaped these characters rather than output them as html would have done.

Here's an example:

To register, you need to enter a user name. This user enters a user name:


<script type="text/javascript">alert('hello');</script>

Assuming that the length of his input is valid, and that django does not explicitly provide any special character conversion method, it would be unsafe to have a window pop up every time it is displayed on the web page.

To solve this problem, django by default converts all special characters to something that can be displayed on html instead of escaping! So, this is what I wanted to print and I couldn't print html.


Related articles: