Django AWS s3 enable file_overwrite only for some files
Django AWS s3 enable file_overwrite only for some files

Django AWS s3 enable file_overwrite only for some files

Here’s a conundrum: what if I want most files to not overwrite in S3, but I want some specific files to be unique and keep their naming? If we enable file_overwrite, all images will keep their name, but if we disable it, then all will be renamed. We might have a parent entity PE1 with a main image, and we want that image to be named PE1-main_image.jpg. How can we achieve that logic only for specific images? The answer is very simple.

During processing, rename your file accordingly.

In your custom storage, set file_overwrite = False and overwrite the get_available_name function:

from storages.backends.s3boto3 import S3Boto3Storage
from storages.utils import get_available_overwrite_name

from web.utils import name_meets_condition

class MediaStorage(S3Boto3Storage):
    location = 'media'
    default_acl = 'public-read'
    file_overwrite = False

    def get_available_name(self, name, max_length=None):
        name = self._clean_name(name)
        if name_meets_condition(name):  # e.g. name.startswith('PE')
            return get_available_overwrite_name(name, max_length)
        
        return super().get_available_name(name, max_length)