如何在新的Django消息框架中的消息中输出HTML? [英] How do I output HTML in a message in the new Django messages framework?

查看:127
本文介绍了如何在新的Django消息框架中的消息中输出HTML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图在通过新的Django消息框架显示的消息中显示一些HTML。具体来说,我通过ModelAdmin.message_user方法来实现,这个方法只是一个关于message()的薄包装:

I'm trying to display a bit of html in a message that's being displayed via the new Django messages framework. Specifically, I'm doing this via the ModelAdmin.message_user method, which is just a thin wrapper around messages():

def message_user(self, request, message):
    """
    Send a message to the user. The default implementation
    posts a message using the django.contrib.messages backend.
    """
    messages.info(request, message)

我尝试过的一切远远似乎显示了转义的HTML。

Everything I've tried so far seems to display escaped HTML.

self.message_user(request, "<a href=\"http://www.google.com\">Here's google!</a>")

不工作,也没有:

from django.utils.safestring import mark_safe
...
self.message_user(request, mark_safe("<a href=\"http://www.google.com\">Here's google!</a>"))

在admin base.html模板中显示的模板代码很简单或者:

The display of the template code in the admin base.html template is pretty straightforward:

    {% if messages %}
    <ul class="messagelist">{% for message in messages %}<li>{{ message }}</li>{% endfor %}</ul>
    {% endif %}

所以我不知道我做错了什么

So I'm not exactly sure what I am doing wrong.

非常感谢,感谢!

推荐答案

另一个选项是使用 extra_tags 关键字arg表示消息是安全的。例如

Another option is to use extra_tags keyword arg to indicate that a message is safe. Eg

messages.error(request, 'Here is a <a href="/">link</a>', extra_tags='safe')

然后使用模板逻辑来使用安全过滤器

then use template logic to use the safe filter

{% for message in messages %}
    <li class="{{ message.tags }}">
    {% if 'safe' in message.tags %}{{ message|safe }}{% else %}{{ message }}{% endif %}
    </li>
{% endfor %}

这篇关于如何在新的Django消息框架中的消息中输出HTML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆