如何防止Django自动转义HTML

3

我通过Django管理面板输入了一个包含嵌入式<a>responsibility.description。在模板中显示时,我希望<a>作为链接出现,而不是被转义为&lt;a&rt;

我找到了这个建议(如何在Django feeds中禁用自动转义?),但似乎对我没有用。

我尝试将其标记为safe

{% for responsibility in software.responsibilities.all %}
    <li>{{ responsibility.description|safe }}</li>
{% endfor %}

同时也要关闭autoescape

{% for responsibility in software.responsibilities.all %}
    {% autoescape off %}
        <li>{{ responsibility.description }}</li>
    {% endautoescape %}
{% endfor %}

我是否遗漏了什么或者还有其他方法可以尝试?

以下是存储在数据库中的数据:

>>> Responsibility.objects.filter(id=38)
<QuerySet [<Responsibility: Created and ran test suites using a proprietary testing framework for “Stubbs the Zombie” (<a target="_blank" href="http://www.imdb.com/title/tt0498128/fullcredits?ref_=tt_cl_sm#cast">credited</a>), a game for Windows, Mac, and X-Box written in C/C++ utilizing the Halo game engine.>]>

以下是它在html中的显示方式:

<li>Created and ran test suites using a proprietary testing framework for "Stubbs the Zombie" (&lt;a target="_blank" href="http://www.imdb.com/title/tt0498128/fullcredits?ref_=tt_cl_sm#cast"&gt;credited&lt;/a&gt;), a game for Windows, Mac, and X-Box written in C/C++ utilizing the Halo game engine.</li>

抱歉,那是我非常愚蠢的西部最快枪手式回答,没有查看就回复了。不过你似乎做得对。你能发布一些示例数据,并展示它现在的样子以及应该如何呈现吗? - e4c5
这是只有<a> 还是类似于<a href="something.com">something</a>这样的东西吗? - Exprator
@e4c5 哈哈,没问题。我之前也做过同样的事情。:) 我添加了数据库中数据的样式以及在HTML中的展示方式。希望对你有所帮助。 - Nick Weseman
@Exprator,对的,就像你建议的那样,如果你想看一下,它是<a href...>。 - Nick Weseman
兄弟,你能做个简单的事吗?我猜那是造成错误的原因。只需移除那些括号,尝试使用安全的方式打印,并告诉我们错误是否仍然存在。 - Exprator
1
我会质疑这个问题。为什么你要将HTML存储在数据库中呢? - Jon Kiparsky
2个回答

1
你可以使用 html's 模块,其中包含 unescape 方法:

将字符串 s 中的所有命名和数字字符引用(例如 >、>、&x3e)转换为相应的 Unicode 字符。

你可以通过以下一种或两种方式使用它:
当你收到要存储在数据库中的数据(POST,PUT等)时: ``` from html import unescape to_be_stored = unescape(input_data) ``` 然后将`to_be_stored`存储在你的数据库中。
当你从数据库发送数据到模板(GET,LIST等)时: ``` from html import unescape class MyView(): ... def get(self): ... responsibility = Responsibility.objects.filter(id=your_id) response['responsibility'] = unescape(responsibility.description) ... ``` 然后返回/渲染等响应。

感谢提供服务器端解决方案,我之前只关注了客户端解决方案。 - Nick Weseman
没问题,伙计 :) - John Moutafis

0

请尝试使用|safe|escape

{% for responsibility in software.responsibilities.all %}
    <li>{{ responsibility.description|safe|escape }}</li>
{% endfor %}

参考: 安全


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接