Django Custom File Storage system

后端 未结 3 1034
我寻月下人不归
我寻月下人不归 2021-02-08 17:38

I have a custom storage

import os
from django.core.files.storage import Storage


class AlwaysOverwriteFileSystemStorage(Storage):
    def get_available_name(sel         


        
3条回答
  •  难免孤独
    2021-02-08 18:11

    You don't need to put anything in your settings.py. Just use it directly in your model. For example, create storage.py wherever your app is located and put OverwriteStorage() in it. Then, your model could look like this:

    from storage import OverwriteStorage
    ...
    class MyModel(models.Model):
        ...
        image = ImageField(upload_to='images', storage=OverwriteStorage())
    

    I am also using a custom storage system to overwrite existing files. My storage.py looks like this:

    from django.core.files.storage import FileSystemStorage
    
    class OverwriteStorage(FileSystemStorage):
        """
        Returns same name for existing file and deletes existing file on save.
        """                                                              
        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
    

提交回复
热议问题