Ranju R
Ranju R

Reputation: 2557

Remove previous image from media folder when ImageFiled entry modified in Django

I have a Model with a ImageField.

class Photo(models.Model):
  ----
  image = models.ImageField(verbose_name=_('Image'),upload_to='images/category/%Y/%m/%d/',
            max_length=200,null=True,blank=True)
  ---

I edited this model and changed the image field by uploading a new image.

My question, Is there a way to delete the previous image from its directory(from media folder) when I updates this entry with new image. I am using django 1.4.3 .

Upvotes: 1

Views: 984

Answers (1)

Timmy O'Mahony
Timmy O'Mahony

Reputation: 53971

You can either use django's signals or simply overwrite the save method on your model. I would write a signal. Something like the following (note that this is untested):

from django.db.models.signals import pre_save
from django.dispatch import receiver

class Photo(models.Model):
     image = ...

@receiver(pre_save, sender=Photo)
def delete_old_image(sender, instance, *args, **kwargs):
    if instance.pk:
        existing_image = Photo.objects.get(pk=instance.pk)
        if instance.image and existing_image.image != instance.image:
            existing_image.image.delete(False)

Upvotes: 5

Related Questions