How to display image from ImageField in ModelAdmin?

1,800 views
Skip to first unread message

Dave

unread,
Sep 29, 2008, 4:51:19 PM9/29/08
to Django users
Hi,

I've been able to somewhat customize the admin page for a record by
using fieldsets and list_display.

Here's the thing though. I have an ImageField which I can show in
list_display (I copied/modified a thumb function) but I can't figure
out how to show the image in the fieldset. I know description allows
arbitrary html, but I can't make calls the thumb function.

Any ideas would be greatly appretiated.

Thanks,

-Dave

krylatij

unread,
Sep 30, 2008, 1:55:23 AM9/30/08
to Django users
I think you need to write custom widget for ImageField


krylatij

unread,
Oct 1, 2008, 4:36:09 PM10/1/08
to Django users
I have written some sample.
it works for me, hope it will be usefull:

from django.contrib.admin.widgets import AdminFileWidget
from django.utils.safestring import mark_safe

class AdminImageFieldWithThumbWidget(AdminFileWidget):
def render(self, name, value, attrs=None):
thumb_html = ''
if value and hasattr(value, "url"):
thumb_html = '<img src="%s" width="60" width="60"/>' %
value.url
return mark_safe("%s%s" % (thumb_html,
super(AdminImageFieldWithThumbWidget, self).render(name, value,
attrs)))
...
class MyModelOptions(admin.ModelAdmin):
...
def formfield_for_dbfield(self, db_field, **kwargs):
if db_field.name == 'image':
from django import forms
return
forms.CharField(widget=AdminImageFieldWithThumbWidget(**kwargs))
return
super(MyModelOptions,self).formfield_for_dbfield(db_field,**kwargs)

volksman

unread,
Oct 16, 2008, 4:13:58 PM10/16/08
to Django users
Beauty in motion! Works like a charm...Thanks!

krylatij

unread,
Oct 17, 2008, 2:36:40 AM10/17/08
to Django users
Code above was a bit incorrect. Here better solution:
## widget declaration
from django.utils.safestring import mark_safe
from django.forms.widgets import FileInput

class AdminImageFieldWithThumbWidget(FileInput):

def __init__(self, thumb_width=50, thumb_height=50):
self.width = thumb_width
self.height = thumb_height
super(AdminImageFieldWithThumbWidget, self).__init__({})

def render(self, name, value, attrs=None):
thumb_html = ''
if value and hasattr(value, "url"):
thumb_html = '<img src="%s" width="%s" width="%s"/>' %
(value.url, self.width, self.height)
return mark_safe("%s%s" % (thumb_html,
super(AdminImageFieldWithThumbWidget, self).render(name, value,
attrs)))


##form sample
class PhotoBaseInline(admin.StackedInline):
fieldsets = (
(None, {'fields': (('photo', 'default'),)}),
)

thumb_width = 50
thumb_height = 50
def formfield_for_dbfield(self, db_field, **kwargs):
field =
super(PhotoBaseInline,self).formfield_for_dbfield(db_field,**kwargs)
if db_field.name == 'photo':
return
forms.ImageField(widget=AdminImageFieldWithThumbWidget(thumb_width=self.thumb_width,
thumb_height=self.thumb_height))
return field
Reply all
Reply to author
Forward
0 new messages