Recently in the study of django, django was used to do a simple website, used to practice, the specific function is to capture data from the Internet, and then placed on my website, but encountered a problem is that django can not be output in html format, can only be output in the form of strings:
data = '<h1>hello world</h1>' <p>{{ data }}</p>
What we aim to output is:
hello world
But the resultant output is:
<h1>hello world</h1>
After searching the internet for a long time, I finally found a solution:
For a single variable use django's filter to tell Django that the string doesn't need to be HTML escaped, as follows:
data | safe
For a piece of template content you can use the autoescape tag, for example:
{% autoescape off %} {{ data }} {% endautoescape %}
The meaning of off is to turn off the escaping of html, while replacing off with on means to escape html, which is done by default.
Note: autoescape is inherited, if it is defined in the parent template, it also exists in the corresponding content section of the child template.
We may wonder why django is escaping these characters instead of outputting them as they were originally html.
Let's take an example:
A user is required to enter a username to register, and this user entered a username:
<script type="text/javascript">alert('hello');</script>
Assuming the length of his input is legal, and django doesn't explicitly provide any special character conversion methods, then every time he displays it on the web page, won't it pop up a window every time, which is not very unsafe.
In order to solve this problem, django defaults to convert all special characters into content that can be displayed in html, and no longer includes the escape function! So, there is also the above I want to output but output but not output html content.
The above example of this django output html content is all I have to share with you, I hope to give you a reference, and I hope you will support me more.