Image file not deleted when object with ImageField field is deleted

。_饼干妹妹 提交于 2019-11-28 09:58:58
Chris Pratt

Deletion of files associated with FileFields and ImageFields was intentionally removed in Django 1.3. See ticket #6456. Django uses transactions extensively to prevent data corruption if something goes wrong with the request. If a deletion transaction is rolled-backed, after the file has been deleted from the filesystem, then you now have a record pointing to a non-existent file. All tickets asking for automatic deletion to return have been summarily marked "Won't Fix", so this is not going to change.

For workarounds, see this previous StackOverflow question.

rh0dium

The assumptions?

class Picture(models.Model):
    image = ImageField(blank=True, null=True, upload_to="pics")

    def delete(self, *args, **kwargs):
        self.image.delete()
        super(Picture, self).delete(*args, **kwargs)

Then lets manually create and delete this..

image = "./image.jpg"
picture = Picture.objects.create(image=File(open(image, "r"))
picture.save()

Then delete it?

picture.delete()

HTH

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!