Search code examples
djangosignals

django signals pre_save when file is uploaded


Can I test in pre_save or post_save, if a file was uploaded / changed?

Example:

class Item(models.Model):
  name_123 = models.CharField(max_length=255)
  photo = models.ImageField()


@receiver(pre_save, sender=Item)
def my_callback(sender, instance, *args, **kwargs):
  if NEW photo was uploaded:
    resize it;

I dont want to resize the image, if only the name_123 changed, but I want to resize it when a new Item was created and when the image changed (even when the same image with the same file name was uploaded.

If I would use a front end CreateView or something similar, I could have check if the form_data contains file data but I want to use it in general (django admin too). Thanks


Solution

  • Check this out you can simply overwrite the model save method to resize the image.

    class Item(models.Model):
        name_123 = models.CharField(max_length=255)
        photo = models.ImageField()
    
    def save(self, *args, **kwargs):
        from django.core.files.uploadedfile import UploadedFile
        if hasattr(self.photo, 'file') and isinstance(self.photo.file, UploadedFile):
            pass
            # Resize your photo here.
            # resized_image = get_image_resized()
            # self.photo = resized_image
        super(Item, self).save(*args, **kwargs)