pythondjangodjango-modelsdjango-adminadmin

Django Admin Show Image from Imagefield


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

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!


Solution

  • 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']