Skip to main content

Command Palette

Search for a command to run...

How To Show Image From Imagefield In Django Admin Page?

How To Show Image In Django Admin?

Published
2 min read
How To Show Image From Imagefield In Django Admin Page?

Note: If you are looking for a Full Stack Developer (Django+React), then connect with me on LinkedIn or contact me through my portfolio.

localhost_8000_catalog_product_.png

As shown in the above image, we can clearly see that we can add an image as a column in the Django admin and show it there.

Let’s check out how can we achieve that.

Here is our model which contains the ImageField along with other fields,

# models.py

class Product(models.Model):
    ...
    image = models.ImageField(upload_to='products')
    ...

Now let’s register this model in the Admin,

# admin.py

...
from django.utils.safestring import mark_safe

@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
    ...
    list_display = (
        ...,
        'product_image'
    )

    @mark_safe
    def product_image(self, obj):
        return f'<img src="{obj.image.url}" height="{obj.image.height}" width="{obj.image.width}" />'

We are using mark_safe as a decorator to render it as an HTML code in the template, because by default Django will render product_image as a simple text if we do not use mark_safe.

One thing to note here is that you can specify other HTML attributes in the img tag, and also you are free to change the values of height and width as per your need.

So this is the simplest way to show the images of ImageField in the Django admin.

Any thoughts? Write it down in the comments.

For more such crispy blogs daily, follow Dev.Junction, subscribe to our newsletter and get notified.

A

if you clear image then it through error . Resolve this error.

Django admin tips and tricks

Part 12 of 14

Django provides a great Admin panel rich in features and highly customizable, in this series of blogs we will be introduced to all such possible customizations and more.

Up next

How to install and setup Django Jet theme?

Customize the Django Admin With a Modern Theme