Django Custom File Storage system

后端 未结 3 1033
我寻月下人不归
我寻月下人不归 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:07

    I try to make this, but don`t work for me, until I make this on my storage.py :

    import os
    from django.conf import settings
    from django.core.files.storage import FileSystemStorage
    
    
    class MyFileSystemStorage(FileSystemStorage):
        def get_available_name(self, name, *args, **kwargs):
            if self.exists(name):
                os.remove(os.path.join(settings.MEDIA_ROOT, name))
            return super().get_available_name(name, *args, **kwargs)
    

    No other changes was required.

    Another way yo do this:

    from django.core.files.storage import FileSystemStorage
    
    class AvatarStorage(FileSystemStorage):
    
        def get_available_name(self, name, *args, **kwargs):
            self.delete(name)
            return super().get_available_name(name, *args, **kwargs)
    

    The delete method check if the file exists. So these 3 line are enough. I hope this help somebody

提交回复
热议问题