Prevent django admin from escaping html

2019-02-05 12:11发布

问题:

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?

回答1:

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


回答2:

I know this is a rather late answer, but I thought a more complete implementation would be helpful to others...

If you don't have it already with django-filer, get 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)