DEV Community 👩‍💻👨‍💻

Vijay Soni
Vijay Soni

Posted on

How to show images of the model in Django Admin?

In this tutorial you will learn how to show image of a django model in the django's admin site.

Suppose we have a model of image in our django website.

class Image(models.Model):
    name = models.CharField(max_length=250)
    image = models.ImageField(upload_to='images/')

    def __str__(self):
Enter fullscreen mode Exit fullscreen mode

And we want that the both fields of the model Image should be shown in our website's admin site.

But if we directly say django admin to show the image in the admin by list_display in it gives us the url of the image , it does not show the image there.

from django.contrib import admin
from .models import Image
class ImageAdmin(admin.ModelAdmin):
    list_display = ['name', 'image',], ImageAdmin)
Enter fullscreen mode Exit fullscreen mode

not showing image only url

So this is not a good approach to do that so we have a quick fix to solve this problem.

from django.utils.html import format_html

class ImageAdmin(admin.ModelAdmin):

    def image_tag(self, obj):
        return format_html('<img src="{}" style="max-width:200px; max-height:200px"/>'.format(obj.image.url))

    list_display = ['name','image_tag',], ImageAdmin)
Enter fullscreen mode Exit fullscreen mode

Showing Images also

You must check if the static and media settings are included in our project/ (main urls file) or not.

# project/
from django.conf import settings 
from django.conf.urls.static import static
from django.urls import path,
urlpatterns = [
    '''your urlpatterns'''
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Enter fullscreen mode Exit fullscreen mode

that's done.

Thank you for reading my post!

Top comments (1)

charlesmichaelvaughn profile image
Charles Michael Vaughn

great article

Find what you were looking for? Sign up so you can:

🌚 Enable dark mode
🔠 Change your default font
📚 Adjust your experience level to see more relevant content