Delete old image when saving new imagefield django
In Django, you can achieve this by overriding the save
method of your model. Here's an example:
from django.db import models
class MyModel(models.Model):
image = models.ImageField(upload_to='images/')
def save(self, *args, **kwargs):
if self.image:
# Delete the old image
old_image = MyModel.objects.filter(id=self.id).first()
if old_image and old_image.image:
old_image.image.delete(save=False)
super().save(*args, **kwargs)
In this example, when you save a new instance of MyModel
, the save
method checks if the image
field has been updated. If it has, it deletes the old image by querying the database for the instance with the same ID, and then deleting the old image file.
Note that we set save=False
when deleting the old image, so that the deletion is not saved to the database immediately. This is to avoid creating a new revision in the database.
Also, make sure to update the upload_to
parameter in your ImageField
to the correct directory where you want to store the images.
Alternatively, you can use a signal to achieve this. You can create a signal that listens for the pre_save
signal, and then delete the old image in the signal handler. Here's an example:
from django.db.models.signals import pre_save
from django.dispatch import receiver
@receiver(pre_save, sender=MyModel)
def delete_old_image(sender, instance, **kwargs):
if instance.image and instance.image!= instance._old_image:
instance._old_image.delete(save=False)
In this example, we define a signal handler that listens for the pre_save
signal sent by the MyModel
model. In the handler, we check if the image
field has been updated, and if it has, we delete the old image. We use the _old_image
attribute to store the old image, and then delete it.
Make sure to add the signal handler to your models.py
file and run makemigrations
and migrate
commands to apply the changes to your database.