简体   繁体   中英

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

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM