Reputation: 799
I have an Image
model where I have typically shown the filename in the __str__
method. I'd like to instead show a thumbnail of the image instead.
Here's my model:
class Image(models.Model):
image = models.ImageField(upload_to='images/')
def filename(self):
return basename(self.image.name)
def __str__(self):
return self.filename()
Upvotes: 0
Views: 231
Reputation: 825
You need to modify your àdmin.py' instead of your models.py
. Do the following code.
In your models.py
class Image(models.Model):
image = models.ImageField(upload_to="images/")
In your admin.py
from PIL import Image
from django.contrib import admin
from django.utils.safestring import mark_safe
class ImageAdmin(admin.ModelAdmin):
list_display = [
"thumbnail", "name"
]
list_display_links = [
"thumbnail"
]
readonly_fields = [
"thumbnail", "name"
]
fieldsets = [
("Details", {
"fields": ("name", ("image", "thumbnail"))
}),
]
def thumbnail(self, obj):
if obj.image:
return mark_safe(
'<img src="/media/{url}" width="75" height="auto" >'.format(
url=obj.image.url.split("/media/")[-1])
)
def name(self, obj):
name = obj.image.name
return name.replace('images/', '')
Below, you can see the result in your admin.
Upvotes: 1