pythondjangodjango-modelsdjango-adminchangelist

How to display uploaded images in "Change List" page in Django Admin?


I'm trying to display uploaded images in "Change List" page in Django Admin:

enter image description here

This is my code below:

# "models.py"

from django.db import models

class Product(models.Model):
    name = models.CharField(max_length=50)
    price = models.DecimalField(decimal_places=2, max_digits=5)
    image = models.ImageField()
        
    def __str__(self):
        return self.name
# "admin.py"

from django.contrib import admin
from .models import Product

@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
    list_display = ('name', 'price', 'image',)

So, how can I display uploaded images in "Change List" page in Django Admin?


Solution

  • You can create a model instance method with another name, allow HTML tags for its output and add this method as a list field. Here is an example:

    First add a new method returning the HTML for the image inclusion:

    class Article(models.Model):
        ...
        def admin_image(self):
            return '<img src="%s"/>' % self.img
        admin_image.allow_tags = True
    

    Then add this method to the list:

    class ArticleAdmin(admin.ModelAdmin):    
        ...
        list_display = ('url', 'title', 'admin_image')