防止django管理员逃避html

时间:2010-07-21 10:03:09

标签: django admin escaping

我正在尝试在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)
尽管我将字符串标记为安全,但管理员仍将缩略图显示为转义的html。我做错了什么?

2 个答案:

答案 0 :(得分:80)

从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)

在早期版本的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

答案 1 :(得分:5)

我知道这是一个相当晚的答案,但我认为更完整的实施会对其他人有所帮助......

如果您还没有使用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)