i'm new to Django and trying to change how inline images are presented in the admin panel. Can I add a Preview tag above each 'Currently' to and show thumbnail?
The simple solution that works for me in Django 3.0:
In models.py add:
from django.utils.safestring import mark_safe
def image_preview(self):
if self.image:
return mark_safe('<img src="{0}" width="150" height="150" />'.format(self.image.url))
else:
return '(No image)'
in admin.py:
class ProductImagesAdmin(admin.TabularInline):
model = ProductImages
readonly_fields = ('image_preview',)
Following on, to @shaniqwa answer, django(2.2.7) now requires renderer in render(),
class AdminImageWidget(AdminFileWidget):
def render(self, name, value, attrs=None, renderer=None):
output = []
if value and getattr(value, "url", None):
image_url = value.url
file_name = str(value)
output.append(
f' <a href="{image_url}" target="_blank">'
f' <img src="{image_url}" alt="{file_name}" width="150" height="150" '
f'style="object-fit: cover;"/> </a>')
output.append(super(AdminFileWidget, self).render(name, value, attrs, renderer))
return mark_safe(u''.join(output))
class ProductImagesAdmin(admin.TabularInline):
model = ProductImages
extra = 1
formfield_overrides = {
models.ImageField: {'widget': AdminImageWidget}
}
Cleaned up version of the first answer https://stackoverflow.com/a/44051507/2020723 - ready of Django >3, python 3.x:
class AdminImageWidget(AdminFileWidget):
"""Admin widget for showing clickable thumbnail of Image file fields"""
def render(self, name, value, attrs=None, renderer=None):
html = super().render(name, value, attrs, renderer)
if value and getattr(value, 'url', None):
html = format_html('<a href="{0}" target="_blank"><img src="{0}" alt="{1}" width="150" height="150" style="object-fit: contain;"/></a>', value.url, str(value)) + html
return html
I managed to do it after a lot of digging. Unfortunately I couldn't find the source I used (too many tabs, too many didn't work..) . So the idea was to create an Image Widget, that appends some html script.
from django.contrib.admin.widgets import AdminFileWidget
class AdminImageWidget(AdminFileWidget):
def render(self, name, value, attrs=None):
output = []
if value and getattr(value, "url", None):
image_url = value.url
file_name = str(value)
output.append(u' <a href="%s" target="_blank"><img src="%s" alt="%s" width="150" height="150" style="object-fit: cover;"/></a> %s ' % \
(image_url, image_url, file_name, _('')))
output.append(super(AdminFileWidget, self).render(name, value, attrs))
return mark_safe(u''.join(output))
class CollectionImageInline(admin.TabularInline):
formfield_overrides = {models.ImageField: {'widget': AdminImageWidget}}
the result : (I changed admin theme to default regardless to this issue)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With