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.
python
# models.py
class Image(models.Model):
name = models.CharField(max_length=250)
image = models.ImageField(upload_to='images/')
def __str__(self):
return self.name
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)
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)
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)
that's done.
Thank you for reading my post!
Top comments (1)
great article