I\'ve defined a model which contains a link an image. Is there a way to display the image in the model items list? My model looks like this:
class Article(mo
UPDATE 2020
Because this answer is getting a lot of traction recently, I decided to make small edit. According to django doc it is recommended to use function format_html. As @chem1st suggested, if you need it only for admin, everything can be made in admin.py only.
My models.py
from django.db import models
class Product(models.Model):
title = models.CharField(max_length=120)
description = models.TextField()
price = models.DecimalField(decimal_places = 2, max_digits = 20, default = 00.00)
image = models.ImageField(upload_to=change_image_name, null=True, blank=True)
def __str__(self):
return self.title
My admin.py
from django.contrib import admin
from django.utils.html import format_html
from .models import Product
class ProductAdmin(admin.ModelAdmin):
list_display = ('title', 'description', 'price', 'image_tag')
def image_tag(self,obj):
return format_html('
'.format(obj.image.url))
admin.site.register(Product, ProductAdmin)
UPDATE django 2.0.6
I was solving this problem in latest django 2.0.6. I wanted to achiave to have image thubnail and some more details in listview in django-admin.
Picture below is my default admin listview.
This is my models.py:
from django.db import models
from django.utils.safestring import mark_safe
# Create your models here.
class Product(models.Model):
title = models.CharField(max_length=120)
description = models.TextField()
price = models.DecimalField(decimal_places = 2, max_digits = 20, default = 00.00)
image = models.ImageField(upload_to=change_image_name, null=True, blank=True)
def image_tag(self):
if self.image:
return mark_safe('
' % self.image.url)
else:
return 'No Image Found'
image_tag.short_description = 'Image'
def __str__(self):
return self.title
Please notice I had to use mark_safe() on image string, otherwise you will get escaped html code instead of thubnail in django-admin
Finally this is my admin.py
from django.contrib import admin
from .models import Product
# Register your models here.
class ProductAdmin(admin.ModelAdmin):
list_display = ('title', 'description', 'price', 'image_tag')
admin.site.register(Product, ProductAdmin)
Here we have to register ProductAdmin class too, I didn't know that and it didn't work.
This is result: