[Django]-How to show BinaryField image preview in Django admin interface?

6👍

Fist, add the code below to your model.

def scheme_image_tag(self):
    from base64 import b64encode
    return mark_safe('<img src = "data: image/png; base64, {}" width="200" height="100">'.format(
        b64encode(self.scheme_image).decode('utf8')
    ))

scheme_image_tag.short_description = 'Image'
scheme_image_tag.allow_tags = True

Then, you can render this field on your list_display (admin).

list_display = (...'scheme_image_tag')

As mentioned by @DmitriyVinokurov, you can add this tag to readonly_fields.

readonly_fields = (..., 'scheme_image_tag')

P.S. This answer explains why I’m using decode('utf8').

Leave a comment