Login

File storage with a better rename method

Author:
SmileyChris
Posted:
July 30, 2009
Language:
Python
Version:
1.1
Score:
2 (after 2 ratings)

A file storage which uses a more sane rename method for existing files.

Add DEFAULT_FILE_STORAGE = 'site.storage.BetterNameFileSystemStorage' (obviously changing site.storage to the module which you put this inside)

 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. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

Please login first before commenting.