Replacing a Django image doesn't delete original

前端 未结 8 1342
死守一世寂寞
死守一世寂寞 2020-12-13 14:43

In Django, if you have a ImageFile in a model, deleting will remove the associated file from disk as well as removing the record from the database.

Shouldn\'t replac

8条回答
  •  清歌不尽
    2020-12-13 15:06

    I save the original file and if it has changed - delete it.

    class Document(models.Model):
        document = FileField()
    
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            self._document = self.document
    
        def save(self, *args, **kwargs):
            if self.document != self._document:
                self._document.delete()
                super().save(*args, **kwargs)
    

提交回复
热议问题