- Author:
- theetderks
- Posted:
- May 16, 2007
- Language:
- Python
- Version:
- .96
- Score:
- 8 (after 8 ratings)
This code will add a thumbnail image to your Model's Admin list view. The code will also generate the thumb images, so the first view may be a little slow loading.
This assumes you have an ImageField in your Model called image, and the field's upload_to directory has a subdirectory called tiny. You then must add "thumb" to your Model's Admin list_display.
The thumbnail images are also linked to the full size view of the image.
I found this VERY useful... hope someone else does as well.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <<add to top of file>>
import os, Image
TINY_SIZE = (80,80) #thumb size (x,y)
<<add to Model>>
def thumb(self):
tinythumb = self.image.replace('\\','/').split('/')
tinythumb[-1] = 'tiny/'+tinythumb[-1]
tinythumb = '/'.join(tinythumb)
if not os.path.exists(MEDIA_ROOT+tinythumb):
im = Image.open(MEDIA_ROOT+self.image)
im.thumbnail(TINY_SIZE,Image.ANTIALIAS)
im.save(MEDIA_ROOT+tinythumb,"JPEG")
return """<a href="/media/%s"><img src="/media/%s" alt="tiny thumbnail image" /></a>"""%(self.image,tinythumb)
thumb.allow_tags = True
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 3 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
Hi all, i did try this code but it doesn't work. This code: im = Image.open(MEDIA_ROOT+self.image) im.thumbnail(TINY_SIZE,Image.ANTIALIAS) im.save(MEDIA_ROOT+tinythumb,"JPEG")
don't generate the thumb in the folder "tiny"... I work with Django on OSX.
Can anyone please help me on this? thanks in advance guys.
#
Marco -
Have you installed and imported PIL (Python Imaging Library called: Image)?
If your not sure, from a python prompt try: import Image
What does your traceback look like?
Thomas
#
Hello,
The same idea in a more correct way:
Of course, you should add "from os import path" at the beginning of the file.
Thanks, Dmitriy
#
And more correct for change list:
models.py
admin.py
#
Please login first before commenting.