Human readable file names decorator

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
def upload_to_dest(path='', human_readable_field='hrfname'):
    def unique_filepath(instance, filename):
        """Generate random unique filename or use name
        from `human_readable_field` if it's available and not empty"""
        fname, ext = os.path.splitext(filename)

        if hasattr(instance, human_readable_field) and \
            getattr(instance, human_readable_field) and \
            getattr(instance, human_readable_field) != '':
            fname_chunk = getattr(instance, human_readable_field)
        else:
            fname_chunk = uuid.uuid4()

        filename = "%s%s" % (fname_chunk, ext.lower())
        return os.path.join(path, filename)
    return unique_filepath

More like this

  1. Admin Image Widget by baumer1122 4 years, 10 months ago
  2. Database file storage by powerfox 4 years, 4 months ago
  3. FileField / ImageField with a delete checkbox by tomZ 5 years, 7 months ago
  4. Updated FileField / ImageField with a delete checkbox by tomZ 5 years, 3 months ago
  5. Load File From URL Widget by bryanhelmig 1 year, 10 months ago

Comments

darek (on April 4, 2011):

Change this:

if hasattr(instance, human_readable_field) and \
    getattr(instance, human_readable_field) and \
    getattr(instance, human_readable_field) != '':

to:

if getattr(instance, human_readable_field, None):

#

(Forgotten your password?)