XSS攻击包括在页面中注入HTML(或JS)代码。有关更多信息,请参见什么是跨站点脚本。
为了防止这种攻击,默认情况下,Django会转义通过模板变量传递的字符串。
鉴于以下情况:
context = {
'class_name': 'large" style="font-size:4000px',
'paragraph': (
"<script type=\"text/javascript\">alert('hello world!');</script>"),
}<p class="{{ class_name }}">{{ paragraph }}</p>
<!-- Will be rendered as: -->
<p class="large" style="font-size: 4000px"><script>alert('hello world!');</script></p>如果您拥有值得信任且实际上想要呈现的包含HTML的变量,则必须明确声明它是安全的:
<p class="{{ class_name|safe }}">{{ paragraph }}</p>
<!-- Will be rendered as: -->
<p class="large" style="font-size: 4000px"><script>alert('hello world!');</script></p>如果您有一个包含多个都安全的变量的块,则可以在本地禁用自动转义:
{% autoescape off %}
<p class="{{ class_name }}">{{ paragraph }}</p>
{% endautoescape %}
<!-- Will be rendered as: -->
<p class="large" style="font-size: 4000px"><script>alert('hello world!');</script></p>您还可以在模板外部将字符串标记为安全:
from django.utils.safestring import mark_safe
context = {
'class_name': 'large" style="font-size:4000px',
'paragraph': mark_safe(
"<script type=\"text/javascript\">alert('hello world!');</script>"),
}<p class="{{ class_name }}">{{ paragraph }}</p>
<!-- Will be rendered as: -->
<p class="large" style="font-size: 4000px"><script>alert('hello world!');</script></p>一些Django实用程序(例如format_html已经返回标记为安全的字符串):
from django.utils.html import format_html
context = {
'var': format_html('<b>{}</b> {}', 'hello', '<i>world!</i>'),
}<p>{{ var }}</p>
<!-- Will be rendered as -->
<p><b>hello</b> <i>world!</i></p>