Django学习路27_HTML转义

谨慎使用

自动渲染语法
{{code|safe}}
urls.py 中添加对应的函数

url(r'getcode',views.getcode)
在 views.py 中添加

def getcode(request):
    code = "<h2> HTML 转义示例 </h2>"
    context_code = {
        'code':code
    }
    return render(request,'getcode.html',context=context_code)
getcode.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Getcode 示例</title>
</head>
<body>
<p>
    {{ code|safe }}
</p>
</body>
</html>


网站注入 js ,除非数据绝对安全,否则不要使用 
{{code|safe}}
在 根目录下,创建静态文件夹, static

建立 JavaScript 文件
添加内容
alert("网站被攻陷~"); 
在 views.py 中添加

def getcode(request):
    code = """
    <h2> HTML 转义示例 </h2>
    
    <script type="text/javascript">
        alert("网站被攻陷了~");
    </script>
    """

    context_code = {
        'code':code
    }
    return render(request,'getcode.html',context=context_code)
在 html 数据中添加

{{code|safe}} 

code 为传递过来的参数

里面有外界注入的 js 代码

 


除非数据绝对安全,不然不要使用 {{ xxx|safe}}

进行自动渲染
autoescape off
不进行自动渲染
autoescape on


<body>
    {% autoescape on %}
        {{ code }}
    {% endautoescape %}
</body>


2020-05-16

猜你喜欢

转载自www.cnblogs.com/hany-postq473111315/p/12898638.html