Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Admin Show Image from Imagefield

While I can show an uploaded image in list_display is it possible to do this on the per model page (as in the page you get for changing a model)?

A quick sample model would be:

Class Model1(models.Model):     image = models.ImageField(upload_to=directory) 

The default admin shows the url of the uploaded image but not the image itself.

Thanks!

like image 277
Jeff_Hd Avatar asked Apr 30 '13 19:04

Jeff_Hd


People also ask

How do I display an image in Django?

How you specify the location of an image in Django is in between {% %}. In between these brackets, you specify static 'images\\Python. png', where Python is the image you want to display which is inside of the images directory in the static directory you create for the current app you are in.


1 Answers

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.

like image 73
Michael C. O'Connor Avatar answered Nov 12 '22 16:11

Michael C. O'Connor