设置模型的 __unicode__ 以在管理中显示 html 标签
在 django 管理中,我有一个带有 raw_id_fields 设置的 ManyToMany 字段的 TabularInline 。它在 html 输入字段旁边显示对象的 unicode()。
我希望它显示电子邮件链接。因此,在模型的 unicode() 函数中,我放入 html 标签来创建链接。但是,它正在显示 html 标签。
有没有办法告诉管理员 unicode 可以安全地显示标签?
我尝试过使用 allowed_tags 属性,但这似乎只是 ModelAdmin 属性。
是否可以在不创建新模板的情况下执行此操作?
编辑:
我已经找到了发生这种情况的确切位置。在:django/contrib/admin/widgets.py的第159行,
return ' <strong>%s</strong>' % escape(truncate_words(obj, 14))
那里的转义是手动转义。我已经测试过删除 escape() 并且它有效。我不喜欢编辑 django 源代码的想法。我怎样才能在不改变源的情况下解决这个问题?
In the django admin I have a TabularInline for a ManyToMany field with a raw_id_fields set. It displays the unicode() of the object next to the html input field.
I would like it to display the an email link. So in the unicode() function of the model, I put in the html tags to create a link. However, it is displaying the html tags.
Is there a way to tell the admin that the unicode is safe to display tags?
I've tried using the allow_tags property but that seems to only be a ModelAdmin property.
Is it possible to do this without creating a new template?
EDIT:
I've found exactly where this is happening. On line 159 of:django/contrib/admin/widgets.py
return ' <strong>%s</strong>' % escape(truncate_words(obj, 14))
The escape there is manually escaping it. I've tested removing the escape() and it works. I don't like the idea of editing the django source. How could I get around this without change the source?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您的目标是仅显示列表视图的电子邮件链接,我建议为列表视图编写一个自定义列,如下所示:
这更好,因为您可能在很多其他地方使用 unicode 调用,而 html可能会在那里引起问题。
If your aim is to just display an email link for the list view, i would suggest writing a custom column for the list view like this:
This is better because you might be using the unicode call at a lot of other places, and the html might cause problems there.
下面是一个示例,其最终结果与使用
SafeUnicode
的 sebpiq 相同,“为了 HTML 输出目的,已专门标记为‘安全’的 unicode 子类。”例如
Here is an example, with same end result as sebpiq's using
SafeUnicode
, "A unicode subclass that has been specifically marked as 'safe' for HTML output purposes."e.g.
您应该尝试 mark_safe 的值你回来了。那么字符串不应该再被转义了!
You should try mark_safe on the value that you return. Then the string shouldn't be escaped anymore !