Admin Image Widget + easy-thumbnails

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
from django.contrib.admin.widgets import AdminFileWidget
from django.utils.translation import ugettext as _
from django.utils.safestring import mark_safe
from django.conf import settings
from PIL import Image
import os

try:
    from easy_thumbnails.files import get_thumbnailer
    def thumbnail(image_path):
        thumbnailer = get_thumbnailer(image_path)
        thumbnail_options = {'crop': True, 'size': (160, 120), 'detail': True, 'upscale':True }
        t=thumbnailer.get_thumbnail(thumbnail_options)
        media_url = settings.MEDIA_URL
        return u'<img src="%s%s" alt="%s" width="160" height="120"/>' % (media_url, t, image_path)
except ImportError:
    def thumbnail(image_path):
        absolute_url = os.path.join(settings.MEDIA_ROOT, image_path)
        return u'<img src="%s" alt="%s" />' % (absolute_url, image_path)

class AdminImageWidget(AdminFileWidget):
    """
    A FileField Widget that displays an image instead of a file path
    if the current file is an image.
    """
    def render(self, name, value, attrs=None):
        output = []
        file_name = str(value)
        if file_name:
            file_path = '%s%s' % (settings.MEDIA_URL, file_name)
            try:            # is image
                Image.open(os.path.join(settings.MEDIA_ROOT, file_name))
                output.append('<a target="_blank" href="%s">%s</a>' % \
                    (file_path, thumbnail(file_name),))
            except IOError: # not image
                output.append('%s <a target="_blank" href="%s">%s</a> <br />%s ' % \
                    (_('Currently:'), file_path, file_name, _('Change:')))
            
        output.append(super(AdminFileWidget, self).render(name, value, attrs))
        return mark_safe(u''.join(output))

More like this

  1. ImageField for admin with thumbnail by semente 4 years, 10 months ago
  2. Image Preview on ImageField in admin by fyaconiello 2 years, 12 months ago
  3. django easy_thumbnails AdminImageWidget by livskiy 1 year, 6 months ago
  4. Admin Image Widget by baumer1122 5 years, 8 months ago
  5. thumbnail an image by limodou 7 years, 1 month ago

Comments

nxvl (on March 14, 2012):

There is a small bug in your code, line 18 must call settings.MEDIA_URL instead of settings.MEDIA_ROOT or it won't show the image

#

(Forgotten your password?)