class AdminImageFieldWithThumbWidget(forms.widgets.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'):
print(value)
thumb_html = '<img src="/static/%s" width="%s" height="%s"/>' % (value.url, self.width, self.height)
return mark_safe("%s%s" % (thumb_html, super(AdminImageFieldWithThumbWidget, self).render(name, value, attrs)))
class CustomUserAdmin(UserAdmin):
def formfield_for_dbfield(self, db_field, **kwargs):
if db_field.name == 'picture':
return forms.ImageField(widget=AdminImageFieldWithThumbWidget(thumb_width = self.thumb_width, thumb_height = self.thumb_height))
return super(CustomUserAdmin,self).formfield_for_dbfield(db_field, **kwargs)
NOTE: I tried adding null=True, blank=True to forms.ImageField however I get errors __init__() got an unexpected keyword argument so I guess I can't use them options. If I comment out the def formfield_for_dbfield(self, db_field, **kwargs): then the ImageField is not required as expected.