And*_*ndy 37 django escaping admin
我正在尝试在django admin的list_display中显示图像缩略图,我这样做:
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)
Run Code Online (Sandbox Code Playgroud)
尽管我将字符串标记为安全,但管理员仍将缩略图显示为转义的html.我究竟做错了什么?
Ala*_*air 81
由于Django的1.9,你可以使用format_html()
,format_html_join()
或allow_tags
在你的方法.有关list_display
详细信息,请参阅文档.
使用问题中的代码mark_safe
将起作用.但是对于像这样的方法来说,更好的选择可能是format_html
逃避参数.
def _get_thumbnail(self, obj):
return format_html(u'<img src="{}" />', obj.admin_thumbnail.url)
Run Code Online (Sandbox Code Playgroud)
在早期版本的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
Run Code Online (Sandbox Code Playgroud)
我知道这是一个相当晚的答案,但我认为更完整的实施会对其他人有所帮助......
如果您还没有使用django-filer,请获取easy_thumbnails pip install easy-thumbnails
.
# -*- coding: utf-8 -*-
from django.contrib import admin
from easy_thumbnails.files import get_thumbnailer
from models import Photo
class PhotoAdmin(admin.ModelAdmin):
list_display = ('_thumbnail', 'title', )
list_display_links = ('_thumbnail', 'title', ) # This makes the icon clickable too
readonly_fields = ('_thumbnail', )
fields = ('title', 'photo', )
def _thumbnail(self, obj):
if obj.photo:
thumbnailer = get_thumbnailer(obj.photo)
thumb = thumbnailer.get_thumbnail({
'crop': True,
'size': (50, 50),
# Sharpen it up a little, since its so small...
'detail': True,
# Put other options here...
})
# Note: we get the actual width/height rather than
# hard-coding 50, 50, just to be DRYer
return u'<img src="%s" alt="thumbnail: %s" width="%d" height="%d"/>' % (thumb.url, obj.photo.name, thumb.width, thumb.height)
else:
return "[No Image]"
# Optional, Provide a nicer label in the display
_thumbnail.short_description = 'Thumbnail'
# Required, leaves the markup un-escaped
_thumbnail.allow_tags = True
admin.site.register(Photo, PhotoAdmin)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
15069 次 |
最近记录: |