在Django管理员更改列表中显示HTML字段 [英] Displaying HTML fields in django admin change list
问题描述
是否可以在模型管理员的change_list模板的字段中使用HTML?
Is there a way to use HTML in fields in a model's admin's change_list template?
例如:我想创建 Site域列可点击,并能够导航到该站点:
For example: I would like to make the Site domain column clickable, and to be able to navigate to that site:
推荐答案
您可以创建函数 clickable_site_domain()
,该函数根据<$的值返回HTML链接。 c $ c> site_domain 。然后,您需要将此方法名称添加到 ModelAdmin.list_display
属性。最后,您需要将字符串标记为安全以避免使用 mark_safe
逃脱HTML。
You can create a function clickable_site_domain()
which returns a HTML link as per the value of site_domain
. Then you need to add this method name to the ModelAdmin.list_display
attribute. Finally, you need to mark the string safe to avoid HTML escaping with mark_safe
.
在Django 1.9之前,您为此功能需要设置 allow_tags = True
以避免HTML转义。 (文档)
Prior to Django 1.9, you would need to set allow_tags=True
for this function to avoid HTML escaping. (Docs)
from django.utils.text import mark_safe # Older versions
from django.utils.html import mark_safe # Newer versions
class MyModelAdmin(admin.ModelAdmin):
list_display = (..,'clickable_site_domain', ..) # add the custom method to the list of fields to be displayed.
def clickable_site_domain(self, obj):
# return HTML link that will not be escaped
return mark_safe(
'<a href="%s">%s</a>' % (obj.site_domain, obj.site_domain)'
)
这篇关于在Django管理员更改列表中显示HTML字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!