防止django管理员转义html [英] Prevent django admin from escaping html
问题描述
from django。 utils.safestring import mark_safe
class PhotoAdmin(admin.ModelAdmin):
fields =('title','image',)
list_display =('title','_get_thumbnail '$)
def _get_thumbnail(self,obj):
return mark_safe(u'< img src =%s/>'%obj.admin_thumbnail.url)
管理员将缩略图显示为转义的HTML,尽管我将字符串标记为安全。我做错了什么?
从Django 1.9开始,您可以使用 format_html()
, format_html_join()
或 allow_tags
。请参阅 list_display
文档了解更多信息。
使用 mark_safe $ c $的问题中的代码c>将工作。然而,像这样的方法,更好的选择可能是
format_html
,这将转义参数。
def _get_thumbnail(self,obj):
return format_html(u'< img src ={}/>',obj.admin_thumbnail.url)
在早期版本的Django中,使用 mark_safe()
将不起作用,Django会逃避输出。解决方案是将方法设置为 allow_tags
属性,其值设置为True。
class PhotoAdmin(admin.ModelAdmin):
fields =('title','image',)
list_display =('title','_get_thumbnail',)
def _get_thumbnail(self,obj):
return u'< img src =%s/>'%obj.admin_thumbnail.url
_get_thumbnail.allow_tags = True
I'm trying to display image thumbnails in django admin's list_display and I am doing it like this:
from django.utils.safestring import mark_safe
class PhotoAdmin(admin.ModelAdmin):
fields = ('title', 'image',)
list_display = ('title', '_get_thumbnail',)
def _get_thumbnail(self, obj):
return mark_safe(u'<img src="%s" />' % obj.admin_thumbnail.url)
Admin keeps displaying the thumbnail as escaped html, although I marked the string as safe. What am I doing wrong?
As of Django 1.9, you can use format_html()
, format_html_join()
, or allow_tags
in your method. See the list_display
docs for more info.
The code in the question using mark_safe
will work. However a better option for methods like these might be format_html
, which will escape arguments.
def _get_thumbnail(self, obj):
return format_html(u'<img src="{}" />', obj.admin_thumbnail.url)
In earlier versions of Django, using mark_safe()
would not work, and Django would escape the output. The solution was to give the method an allow_tags
attribute with the value set to True.
class PhotoAdmin(admin.ModelAdmin):
fields = ('title', 'image',)
list_display = ('title', '_get_thumbnail',)
def _get_thumbnail(self, obj):
return u'<img src="%s" />' % obj.admin_thumbnail.url
_get_thumbnail.allow_tags = True
这篇关于防止django管理员转义html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!