Login

Image Preview on ImageField in admin

Author:
fyaconiello
Posted:
April 21, 2011
Language:
Python
Version:
1.3
Score:
-1 (after 1 ratings)

This makes a 100x100 thumbnail of the image for the image field and shows it in the admin form

combination of http://djangosnippets.org/snippets/955/ and http://www.psychicorigami.com/2009/06/20/django-simple-admin-imagefield-thumbnail/

 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
41
42
43
44
45
from django.contrib.admin.widgets import AdminFileWidget
from django.utils.translation import ugettext as _
from django.utils.safestring import mark_safe
import os
import Image

class AdminImageWidget(AdminFileWidget):
	def render(self, name, value, attrs=None):
		output = []
		if value and getattr(value, "url", None):
			
			image_url = value.url
			file_name=str(value)
			
			# defining the size
			size='100x100'
			x, y = [int(x) for x in size.split('x')]
			
			# defining the filename and the miniature filename
			filehead, filetail 	= os.path.split(value.path)
			basename, format 	= os.path.splitext(filetail)
			miniature 		= basename + '_' + size + format
			filename 		= value.path
			miniature_filename 	= os.path.join(filehead, miniature)
			filehead, filetail 	= os.path.split(value.url)
			miniature_url 		= filehead + '/' + miniature
			
			# make sure that the thumbnail is a version of the current original sized image
			if os.path.exists(miniature_filename) and os.path.getmtime(filename) > os.path.getmtime(miniature_filename):
				os.unlink(miniature_filename)
				
			# if the image wasn't already resized, resize it
			if not os.path.exists(miniature_filename):
				image = Image.open(filename)
				image.thumbnail([x, y], Image.ANTIALIAS)
				try:
					image.save(miniature_filename, image.format, quality=100, optimize=1)
				except:
					image.save(miniature_filename, image.format, quality=100)
			
			output.append(u' <div><a href="%s" target="_blank"><img src="%s" alt="%s" /></a></div> %s ' % \
			(miniature_url, miniature_url, miniature_filename, _('Change:')))
			
		output.append(super(AdminFileWidget, self).render(name, value, attrs))
		return mark_safe(u''.join(output))

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

kernel32ddl (on April 21, 2011):

Hi, what is the module "Image"?

#

TheEditor (on March 25, 2012):

How about a short example to show us how this is used? Hardly anybody ever does that around here.

#

Please login first before commenting.