【问题标题】:Display unescaped HTML String in Django Admin change list在 Django Admin 更改列表中显示未转义的 HTML 字符串
【发布时间】:2011-03-25 05:04:19
【问题描述】:

我目前面临一个严重的问题。 我使用标准的 django 管理界面,包括。更改列表以显示我的模型之一。 该模型有一个字段,其中包含一个链接(例如在数据库中:http://localhost:8000/data/somefile.pdf'>link)。

我现在想要的是这个字符串被呈现为非转义并显示为链接。我已经在“change_list_results.html”中尝试了以下内容:

{% for result in results %}
<tr id="{{ result.1|adminfilter }}" class="{% cycle 'row1' 'row2' %}">
    {% for item in result %}
        {{ item|safe }}
    {% endfor %}</tr>
{% endfor %}

我在输出的实际项目上使用了“|safe”。此外,我尝试了“{% autoescape off %}”。同样的结果,字符串被转义了。

你有没有其他方法可以让字符串不转义显示?

【问题讨论】:

    标签: django django-admin django-templates escaping


    【解决方案1】:

    你想在你的方法上设置allow_tags=True。它有点隐蔽,但它在文档中有所描述 - 大约从 this link 带你的地方向下大约一个屏幕。

    【讨论】:

    • 丹尼尔,感谢您的提示。我必须在模型中定义一个返回链接的方法并标记这个 method.allow_tags = True。
    • 因为链接,答案还是正确的。但是allow_tags 在 Django 1.9 中已被弃用。请改用format_html()Deprecated since version 1.9: In older versions, you could add an allow_tags attribute to the method to prevent auto-escaping. This attribute is deprecated as it’s safer to use format_html(), format_html_join(), or mark_safe() instead.docs.djangoproject.com/en/dev/ref/contrib/admin/…
    猜你喜欢
    • 2011-04-29
    • 1970-01-01
    • 1970-01-01
    • 2019-10-20
    • 2018-07-09
    • 2013-05-05
    • 2011-10-12
    • 2013-08-28
    • 2011-03-05
    相关资源
    最近更新 更多