Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
301 views
in Technique[技术] by (71.8m points)

Prevent django admin from escaping html

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?

question from:https://stackoverflow.com/questions/3298083/prevent-django-admin-from-escaping-html

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...