Fabrizio A
Fabrizio A

Reputation: 3172

django replace old image uploaded by ImageField

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

Answers (2)

younesfmgtc
younesfmgtc

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

Anup
Anup

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))

  1. Write a cron job to purge all the unreferenced files. But then again if disk space is a issue, you might want to do the 1st one, that will get you some delay in page load.

Upvotes: 1

Related Questions