Django Admin Show Image from Imagefield
Sure. In your model class add a method like:
def image_tag(self):
from django.utils.html import escape
return u'<img src="%s" />' % escape(<URL to the image>)
image_tag.short_description = 'Image'
image_tag.allow_tags = True
and in your admin.py
add:
fields = ( 'image_tag', )
readonly_fields = ('image_tag',)
to your ModelAdmin
. If you want to restrict the ability to edit the image field, be sure to add it to the exclude
attribute.
Note: With Django 1.8 and 'image_tag' only in readonly_fields it did not display. With 'image_tag' only in fields, it gave an error of unknown field. You need it both in fields and in readonly_fields in order to display correctly.
It can be done in admin without modifying model
from django.utils.html import format_html
@admin.register(Model1)
class Model1Admin(admin.ModelAdmin):
def image_tag(self, obj):
return format_html('<img src="{}" />'.format(obj.image.url))
image_tag.short_description = 'Image'
list_display = ['image_tag',]
In addition to the answer of Michael C. O'Connor
Note that since Django v.1.9 (updated - tested and worked all the way to Django 3.0)
image_tag.allow_tags = True
is deprecated and you should use format_html(), format_html_join(), or mark_safe() instead
So if you are storing your uploaded files in your public /directory folder, your code should look like this:
from django.utils.html import mark_safe
Class Model1(models.Model):
image = models.ImageField(upload_to=directory)
def image_tag(self):
return mark_safe('<img src="/directory/%s" width="150" height="150" />' % (self.image))
image_tag.short_description = 'Image'
and in your admin.py add:
fields = ['image_tag']
readonly_fields = ['image_tag']