views:

25

answers:

1

I have a model that has an option photo field. When a photo is added, I want a thumbnail to be automatically created and stored. However, when I do this with a pre_save signal, I keep getting an IOError, and if I try to do it with a post_save signal I can't save the thumbnails path to my model without creating and infinite post_save loop.

Here's the code

# using PIL 
from PIL import Image
import os
...

# my model
class Course(models.Model):
    ...
    photo = models.ImageField(upload_to='course_images/', blank=True, null=True)
    thumbnail = models.ImageField(upload_to='course_images/thumbnails/', blank=True, null=True, editable=False)
    ...

# my pre_save signal
def resize_image(sender, instance, *args, **kwargs):
    '''Creates a 125x125 thumbnail for the photo in instance.photo'''
    if instance.photo:
        image = Image.open(instance.photo.path)
        image.thumbnail((125, 125), Image.ANTIALIAS)
        (head, tail) = os.path.split(instance.photo.path)
        (a, b) = os.path.split(instance.photo.name)
        image.save(head + '/thumbnails/' + tail)
        instance.thumbnail = a + '/thumbnails/' + b

models.signals.pre_save.connect(resize_image, sender=Course)
+1  A: 

I figured it out. The problem I was having was trying to save the thumbnail field, and I was trying to do that within a signal. So to fix that I save the thumbnail field in the models save() function instead, and leave the signal to create the thumbnail.

Just took me awhile to figure out :/

Abe
Hmm, have you considered using something like [django-photologue](http://code.google.com/p/django-photologue/)?
rebus