Created
June 7, 2012 15:47
-
-
Save igniteflow/2889573 to your computer and use it in GitHub Desktop.
Displaying HTML in Django admin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
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
@Dooweed
Having learnt a bit more since my previous comment, I believe the better way of doing this now is to use
format_html(<html here>)
Just need to import:
from django.utils.html import format_html
Hope that helps 😊