How to delete old image when update ImageField?

前端 未结 8 1567
被撕碎了的回忆
被撕碎了的回忆 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:29

    try this, it will work even if old file is deleted

    def logo_file(instance, filename):
    
        try:
            this = business.objects.get(id=instance.id)
            if this.logo is not None:
                path = "%s" % (this.logo)
                os.remove(path)
        finally:
            pass..
    

    code will work even without "try .. finally" but it will generate problem if file was accidently deleted. changed: move model matching inside "try" so it will not throw any error at user signup Let me know if there are any problems.

提交回复
热议问题