Replacing a Django image doesn't delete original

前端 未结 8 1306
死守一世寂寞
死守一世寂寞 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:00

    Here is a code that can work with or without upload_to=... or blank=True, and when the submitted file has the same name as the old one.

    (py3 syntax, tested on Django 1.7)

    class Attachment(models.Model):
    
        document = models.FileField(...)  # or ImageField
    
        def delete(self, *args, **kwargs):
            self.document.delete(save=False)
            super().delete(*args, **kwargs)
    
        def save(self, *args, **kwargs):
            if self.pk:
                old = self.__class__._default_manager.get(pk=self.pk)
                if old.document.name and (not self.document._committed or not self.document.name):
                    old.document.delete(save=False)
            super().save(*args, **kwargs)
    

    Remember that this kind of solution is only applicable if you are in a non transactional context (no rollback, because the file is definitively lost)

提交回复
热议问题