0👍
✅
I’ve solved the problem but I feel like there should be a more elegant solution.
class AdminImageWidget(forms.FileInput):
"""
A ImageField Widget for admin that shows a thumbnail.
"""
def __init__(self, attrs={}, *args, **kwargs):
super(AdminImageWidget, self).__init__(attrs)
def render(self, name, value, attrs=None):
output = []
file_name = unicode(value)
if file_name:
pattern = re.compile('.png', re.IGNORECASE)
val = '/media/photos_cache/' + pattern.sub('_admin_thumbnail.png', file_name)
output.append(('<a target="_BLANK" href="%s">'
'<img src="%s" /></a> '
% (val, val)))
output.append(super(AdminImageWidget, self).render(name, value, attrs))
return mark_safe(u''.join(output))
The problem is you’ll have to pre-cache the thumbnails.
EDIT:
Strange… Now it works…
class AdminImageWidget(forms.FileInput):
def __init__(self, attrs={}, *args, **kwargs):
super(AdminImageWidget, self).__init__(attrs)
def render(self, name, value, attrs=None):
output = []
file_name = unicode(value)
if file_name:
photo = Photo.objects.get(original_image=file_name)
val = photo.admin_thumbnail.url
output.append(('<a target="_BLANK" href="%s">'
'<img src="%s" /></a> '
% (val, val)))
output.append(super(AdminImageWidget, self).render(name, value, attrs))
return mark_safe(u''.join(output))
1👍
What exactly are you trying to do?
You should find another way to grab the image name. This method ‘render’ is called all the time by Django, even when the field itself is invalid. e.g.:
- I upload ‘me.png’ file in the admin.
- Click save
- Django finds that another field in the admin is incorrect and returns the form to me.
- He calls the render method with ‘me.png’ as the value parameter.
- You get an exception, since this models wasn’t even saved yet.
There are other ways to get the filename, you could override the save method and get the object instance for example.
- [Django]-How to filter a Django QuerySet's related fields' 'all' or 'none'
- [Django]-Django Test – South migration reports 'no such table' but I can see said table in the db
- [Django]-Force re-collectstatic with django static?
- [Django]-Django saving form strings in database with extra characters (u'string')
Source:stackexchange.com