Skip to content

Instantly share code, notes, and snippets.

@igniteflow
Created June 7, 2012 15:47
Show Gist options
  • Save igniteflow/2889573 to your computer and use it in GitHub Desktop.
Save igniteflow/2889573 to your computer and use it in GitHub Desktop.
Displaying HTML in Django admin
from django.utils.safestring import SafeUnicode
"""
When overriding Django admin templates |safe and autoescape off don't work, so do this instead...
"""
# for a foreign key field in the change form, if you want to override the unicode method, use a proxy
class UserProxy(User):
"""
Using a proxy to present the required formatting: username, email, full name
"""
class Meta:
proxy = True
def _get_mailto_link(self, subject=''):
return '<a href="mailto:%s?Subject=%s">Email this user</a>' % (self.email, subject)
def __unicode__(self):
profile = self.get_profile()
return SafeUnicode('%s<br /> %s<br /> %s<br />' % (self.username, self._get_mailto_link(), profile.full_name))
# in list display
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
@ykshatroff
Copy link

In Django >= 2.0, you only need to wrap the return value of your field function with mark_safe:

from django.utils.safestring import mark_safe
class ModelAdmin...:
    def your_html_field(self, obj):
        return mark_safe('<image src="%s" />' % obj.image)

allow_tags no longer needed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment