【问题标题】:How to prevent Django from autoescaping html如何防止 Django 自动转义 html
【发布时间】:2017-05-08 04:31:02
【问题描述】:

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

我找到了这个建议 (How to disable autoescape in 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 哈哈,没问题。我自己之前也做过同样的事情。 :) 我添加了数据在数据库中的样子以及它在 html 中的样子。希望对您有所帮助。
  • @Exprator,是的,如果你想看看,就像你建议的那样
  • 我会质疑这个问题。为什么要在数据库中存储 html?

标签: python django python-3.x


【解决方案1】:

你可以使用html's模块,unescape方法女巫:

转换所有命名和数字字符引用(例如 >、>、 &x3e;) 在字符串 s 中对应 unicode 字符。

您可以通过以下一种或两种方式使用它:

  1. 当您收到要存储在数据库中的数据时(POSTPUT 等):

    from html import unescape
    
    to_be_stored = unescape(input_data)
    

    然后将to_be_stored 存储在您的数据库中

  2. 当您将数据从数据库发送到模板时(GETLIST 等):

    from html import unescape
    
    class MyView():
        ...
        def get(self):
            ...
            responsibility = Responsibility.objects.filter(id=your_id)
            response['responsibility'] = unescape(responsibility.description)
            ...
    

    然后return/render/等回复。

【讨论】:

  • 感谢服务器端解决方案,只关注客户端解决方案。
  • 没问题的伙伴:)
猜你喜欢
  • 2012-04-13
  • 2012-02-05
  • 1970-01-01
  • 2011-03-18
  • 2021-09-10
  • 2018-02-17
  • 1970-01-01
  • 2014-01-13
  • 1970-01-01
相关资源
最近更新 更多