How to delete old image when update ImageField?

前端 未结 8 1571
被撕碎了的回忆
被撕碎了的回忆 2020-12-13 09:20

I\'m using Django to create a stock photo site, I have an ImageField in my model, the problem is that when the user updates the image field, the original image file isn\'t d

8条回答
  •  独厮守ぢ
    2020-12-13 09:31

    Use this custom save method in your model:

    def save(self, *args, **kwargs):
        try:
            this = MyModelName.objects.get(id=self.id)
            if this.MyImageFieldName != self.MyImageFieldName:
                this.MyImageFieldName.delete()
        except: pass
        super(MyModelName, self).save(*args, **kwargs)
    

    It works for me on my site. This problem was bothering me as well and I didn't want to make a cleanup script instead over good bookkeeping in the first place. Let me know if there are any problems with it.

提交回复
热议问题