On Jul 23, 11:07 am, Chris Hoeppner <[EMAIL PROTECTED]> wrote: > Hi there! > > I haven't been able to find this documented anywhere (and I'll kindly > apologize if there actually *is* some doc about it), and thought I'd > turn to you guys ;) > > I'd like to override a model's save() method in order to "thumbnailize" > the data from an image field. Users are able to upload images for > certain model's instances, and I'd like to keep them on a certain size, > no mater what they send me. >
Here's what I did: I added a thumb.py to my app directory with the following code: from PIL import Image from os.path import splitext def get_default_thumbnail_filename(filename): path, ext = splitext(filename) return path + '.thumb' + ext def thumbnail(filename, size=(120, 120), output_filename=None): image = Image.open(filename) if image.mode not in ('L', 'RGB'): image = image.convert('RGB') image.thumbnail(size, Image.ANTIALIAS) # get the thumbnail data in memory. if not output_filename: output_filename = get_default_thumbnail_filename(filename) image.save(output_filename, image.format) return output_filename And then I have this in my model: class ImageSeriesItem(models.Model): class Admin: pass def __str__(self): return self.description[:50] description = models.CharField(maxlength=255) missing = models.BooleanField(default=False) has_image = models.BooleanField(default=True) created = models.DateField() modified = models.DateField(auto_now=True) image_file = models.ImageField(upload_to="imagearchive/%Y/%m/%d") series = models.ForeignKey(ImageSeries) number = models.IntegerField() thumbnail = models.CharField(maxlength=255, editable=False) def save(self): f = create_thumbnail(os.path.join(MEDIA_ROOT, self.image_file)) self.thumbnail = f.replace(MEDIA_ROOT,MEDIA_URL + os.path.sep) super(ImageSeriesItem, self).save() I am no guru, however, and welcome criticism of this code. Some of what I have was borrowed from various places, in particular (thanks, limodou): http://www.djangosnippets.org/snippets/20/ See: http://code.djangoproject.com/wiki/ThumbNails for more discussion. - syd --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~----------~----~----~----~------~----~------~--~---