我正在尝试添加带有来自 Django 管理站点的图像的帖子,但安全/自动转义关闭过滤器无法解释 Django 的模板标签。
My input and page look like:
“复制图像地址”给出http://127.0.0.1:8000/%7B%%20static%20 http://127.0.0.1:8000/%7B%%20static%20'post/image.jpg'%20%%7D
我的视图继承自通用 ListView。
我的base.html和post_list.html:
<!DOCTYPE html>
{% load static %}
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div style="color: red;">
<a href="{% url 'admin:index' %}">admin</a>
{% block contents %}
{% endblock %}
</div>
</body>
</html>
{% extends 'post/base.html' %}
{% block contents %}
{% for post in object_list %}
{% autoescape off %}{{ post.text }}{% endautoescape %}
{{ post.text|safe }}
{% endfor %}
{% endblock %}
您无法直接在模板中执行您想要执行的操作。 Django 模板由“节点”组成,这些“节点”随后被解析为字符串。节点使用{{ variable }}
语法总是返回一个字符串:即使您使用safe
过滤器,Django 不会尝试转换你的post.text
字符串到要由模板引擎呈现的节点中。
您可以通过手动将文本渲染为 Django 模板来在视图中解决此问题:
from django.template import Template
class MyListView(ListView):
#...your existing code
def get_context_data(self, **kwargs):
context = super(MyListView, self).get_context_data(**kwargs)
for post in context["object_list"]:
post.rendered_text = Template(post.text).render(context)
return context
然后在你的模板中:
{% for post in object_list %}
{{ post.rendered_text|safe }}
{% endfor %}
但要小心!从安全角度来看,这是一个非常糟糕的主意!这safe
标签已经相当危险,因为它允许跨站点脚本攻击:任何有权创建帖子的人都可以注入向用户显示的恶意 JavaScript。这个额外的渲染步骤更加危险,因为它还允许访问 Django 模板语言和视图的所有上下文,这可能会访问服务器端机密。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)