Admin Image Widget

 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
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 sorl.thumbnail.main import DjangoThumbnail
    def thumbnail(image_path):
        t = DjangoThumbnail(relative_source=image_path, requested_size=(200,200))
        return u'<img src="%s" alt="%s" />' % (t.absolute_url, 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><br />%s <a target="_blank" href="%s">%s</a><br />%s ' % \
                    (file_path, thumbnail(file_name), _('Currently:'), file_path, file_name, _('Change:')))
            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. Load File From URL Widget by bryanhelmig 1 year, 10 months ago
  2. Human readable file names decorator by maxk 2 years, 2 months ago
  3. ImageField for admin with thumbnail by semente 4 years ago
  4. Updated FileField / ImageField with a delete checkbox by tomZ 5 years, 3 months ago
  5. FileField / ImageField with a delete checkbox by tomZ 5 years, 7 months ago

Comments

KpoH (on August 1, 2008):

thank you!

#

KpoH (on August 1, 2008):

I've made changes, now it's with thumbnail produces by sorl-thumbnail

from sorl.thumbnail.main import DjangoThumbnail

def thumbnail(image_path):
    t = DjangoThumbnail(relative_source=image_path, requested_size=(80, 80))
    return u'<img src="%s" alt="%s">' % (t.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 = []
        if value:
            file_path = '%s%s' % (settings.MEDIA_URL, value)
            try:
                output.append('<a target="_blank" href="%s">%s</a><br />' %
                        (file_path, thumbnail(value)))
            except IOError:
                output.append('%s <a target="_blank" href="%s">%s</a> <br />%s ' %
                        ('Currently:', file_path, value, 'Change:'))

        output.append(super(AdminImageWidget, self).render(name, value, attrs))
        return mark_safe(u''.join(output))

#

baumer1122 (on August 14, 2008):

updated for filestorage refactor and will use sorl.thumbnail if it is available

#

mikko (on September 10, 2008):

Hi, I have put something like this in my new project sorl-curator, Check it out!

#

ellis (on August 2, 2009):

Works great! Thanks for this.

One thing: Your example references "AdminThumbnailWidget" when it should be "AdminImageWidget".

#

asinox (on August 19, 2009):

Hi, how ill use it? where save this code?

Thanks

#

stan (on November 10, 2009):

Line 15 in render: absolute_url = os.path.join(settings.MEDIA_ROOT, image_path

It is MEDIA_URL. You don't want to have src="/home/media/../pamela.jpg".

Regards.

#

nemesis (on January 28, 2010):

Hey, really cool, but i'm missing one simple thing.. Where do i have to save this code? I mean how do i add a custom widget? I've been browsing the documentation but still couldn't understand this little simple thing. I noticed widgets are stored in "site-packages/django/contrib/admin/widgets.py" but really, i guessed i don't have to edit that file but create another one somewhere in my project directory. Am I right? It's driving me mad! Help

#

gamesbook (on March 16, 2010):

Hi

class FileUploadForm(forms.ModelForm):

upload = forms.FileField(widget=AdminThumbnailWidget)

should be

class FileUploadForm(forms.ModelForm):

upload = forms.FileField(widget=AdminImageWidget)

#

jcushman (on August 21, 2010):

I think the non-sorl fallback has a bug:

absolute_url = os.path.join(settings.MEDIA_ROOT, image_path)

should be

absolute_url = os.path.join(settings.MEDIA_URL, image_path)

Thanks!

#

bendavis78 (on August 22, 2010):

You should be referencing the storage settings used by the field's "storage" parameter instead of MEDIA_ROOT and MEDIA_URL, as Django allows those to be overridden with custom storage.

#

KStevens (on December 26, 2012):

Line 15 in render: absolute_url = os.path.join(settings.MEDIA_ROOT, image_path

I can verify this is the correct way to do it. Otherwise you are referencing the wrong url, not where the media is.

#

ageem (on April 10, 2013):

I found too many usefull script here, just learning all. Thank you so much. cara cepat hamil

#

siblek31 (on April 13, 2013):

Alternatives of the latter type are often the result of education reform and are rooted in various philosophies that are commonly fundamentally different from those of traditional compulsory education. While some have strong political, scholarly, or philosophical orientations, others are more informal associations of teachers and students dissatisfied with certain aspects of traditional education. tips cepat hamil These alternatives, which include charter schools, alternative schools, independent schools, homeschooling and soal ulangan harian sd autodidacticism vary, but often emphasize the value kursus bahasa inggris murah of small class size, close relationships between students and teachers, and a sense of community.

Alternative education may also allow for independent learning and engaging class teknisi komputer activities.[10]

#

(Forgotten your password?)