Djano 默认的安全机制会把后台直接发到前端的数据都当做字符串,这样可以有效避免XSS***。
比如说
views.py 片段里面我传递给前端了一个html格式的字符串和一个Javascript的字符串
def tpl4(request):
name = "hello my name is ggggg"
test="""
<input type=text placeholder='UserName' \>
<input type=password placeholder='Password' \>
<input type=submit \>
"""
data="<script>alert(123)</script>"
return render(request, 'tpl4.html', {'name': name,'test':test,'data':data})
tpl4.html 里面直接输出
{% load calculation %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<p>
{% addnum 2 5 6 %}
</p>
<p>
{{ name }}
</p>
<p>
{{ name|upper }}
</p>
<p>
{{ name|truncatechars:"10" }}
</p>
{{ 30|mulnum:30 }}
<p>
{{ test }}
{{ data }}
</p>
</body>
</html>
可以看见结果直接输出的是字符串
如何能够强制解析我们发送的内容呢?我们可以标记他为‘安全’,这样Django的模板语言就能正常识别了。比如我们加一个管道符号,然后表明safe
{% load calculation %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<p>
{% addnum 2 5 6 %}
</p>
<p>
{{ name }}
</p>
<p>
{{ name|upper }}
</p>
<p>
{{ name|truncatechars:"10" }}
</p>
{{ 30|mulnum:30 }}
<p>
{{ test }}
{{ data }}
</p>
<p>
{{ test|safe}}
</p>
{{ data|safe }}
</body>
</html>
这样我就能成功地执行Javascript和html代码了
不过这样每一行来写safe比较麻烦,另外一个简单的方式就是直接在Python文件上标明。
首先要导入一个类 from django.utils.safestring import mark_safe
然后把对应的字符串标记为安全 mark_safe(test)就行了
def tpl4(request):
from django.utils.safestring import mark_safe
name = "hello my name is ggggg"
test="""
<input type=text placeholder='UserName' \>
<input type=password placeholder='Password' \>
<input type=submit \>
"""
data="<script>alert(123)</script>"
test=mark_safe(test)
data=mark_safe(data)
return render(request, 'tpl4.html', {'name': name,'test':test,'data':data})
tpl4.html直接调用即可
{% load calculation %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<p>
{% addnum 2 5 6 %}
</p>
<p>
{{ name }}
</p>
<p>
{{ name|upper }}
</p>
<p>
{{ name|truncatechars:"10" }}
</p>
{{ 30|mulnum:30 }}
<p>
{{ test }}
{{ data }}
</p>
</body>
</html>
效果如下