How To Show Image From Imagefield In Django Admin Page?

How To Show Image From Imagefield In Django Admin Page?

How To Show Image In Django Admin?

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.

Did you find this article valuable?

Support Dev.Junction by becoming a sponsor. Any amount is appreciated!