File storage with a better rename method

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
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

More like this

  1. Database file storage by powerfox 4 years, 3 months ago
  2. Whitelisted overwriting FileSystemStorage by nickma_at 1 year, 9 months ago
  3. Overwriting file storage by wolever 2 years, 9 months ago
  4. TestCase base class to easily temporarily change module values by SmileyChris 2 years, 10 months ago
  5. "an" filter by SmileyChris 4 years ago

Comments

(Forgotten your password?)