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)