Reputation: 3172
How I can replace one image uploaded by an ImageField (in my models) with the new one selected by the same ImageField?
And, can I delete all images uploaded by an ImageField when I delete the model object (bulk delete)?
Upvotes: 0
Views: 1800
Reputation: 19
After hours of searching I found this code. It worked for me in Django 3
class Image(models.Model):
image = models.ImageField()
def save(self, *args, **kwargs):
try:
this = Image.objects.get(id=self.id)
if this.image != self.image:
this.image.delete(save=False)
except:
pass # when new photo then we do nothing, normal case
super().save(*args, **kwargs)
Upvotes: 2
Reputation: 753
This might get tricky, And a lot of times depends on what are your constraints. 1. Write your own save method for the model and then delete the old image a and replace with a new one. os.popen("rm %s" % str(info.photo.path))
Upvotes: 1