import os from django.core.files.storage import FileSystemStorage class BetterNameFileSystemStorage(FileSystemStorage): def get_available_name(self, name): """ Returns a filename that's free on the target storage system, and available for new content to be written to. """ root, file_ext = os.path.splitext(name) root = root.rstrip('_') # If the filename already exists, try again with "filename_2.ext", then # "filename_3.ext", etc. count = 1 while self.exists(name): count += 1 # file_ext includes the dot. name = '%s_%s%s' % (root, count, file_ext) return name