Replacing a Django image doesn't delete original

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

    The code in the following working example will, upon uploading an image in an ImageField, detect if a file with the same name exists, and in that case, delete that file before storing the new one.

    It could easily be modified so that it deletes the old file regardless of the filename. But that's not what I wanted in my project.

    Add the following class:

    from django.core.files.storage import FileSystemStorage
    class OverwriteStorage(FileSystemStorage):
        def _save(self, name, content):
            if self.exists(name):
                self.delete(name)
            return super(OverwriteStorage, self)._save(name, content)
    
        def get_available_name(self, name):
            return name
    

    And use it with ImageField like so:

    class MyModel(models.Model):
        myfield = models.ImageField(
            'description of purpose',
            upload_to='folder_name',
            storage=OverwriteStorage(),  ### using OverwriteStorage here
            max_length=500,
            null=True,
            blank=True,
            height_field='height',
            width_field='width'
        )
        height = models.IntegerField(blank=True, null=True)
        width = models.IntegerField(blank=True, null=True)
    

提交回复
热议问题