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.

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

    def __str__(self):
        return self.name
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 admin.py it gives us the url of the image , it does not show the image there.

# admin.py
from django.contrib import admin
from .models import Image
class ImageAdmin(admin.ModelAdmin):
    list_display = ['name', 'image',]

admin.site.register(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.

# admin.py
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',]

admin.site.register(Image, ImageAdmin)
Enter fullscreen mode Exit fullscreen mode

Showing Images also

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

# project/urls.py
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!

Oldest comments (1)

Collapse
 
charlesmichaelvaughn profile image
Charles Michael Vaughn

great article