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 5 years, 8 months ago
  2. Validation for full e-mails (e.g. "Joe Hacker <joe@hacker.com>") by akaihola 2 years, 4 months ago
  3. Read only form & model field by StanislavKraev 2 years, 9 months ago
  4. Simple Plone Migration by msm-art 6 years, 3 months ago
  5. load m2m fields objects by dirol 3 years, 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?)