Login

Human readable file names decorator

Author:
maxk
Posted:
April 1, 2011
Language:
Python
Version:
1.2
Tags:
django ImageField file uploads file name FileField
Score:
0 (after 0 ratings)

This is extremely simple decorator to add possibility to upload files with name specific in some object field. For example image with same name as object slug.

Sample model:

class Test(models.Model):
    image = models.ImageField(\
        upload_to=upload_to_dest(path='pics/', \
        human_readable_field='hrname'))
    hrname = models.CharField( \
        max_length=128, \
        blank=True, default='')

Sample form for admin:

FNAME_EXP = re.compile('^[A-Za-z0-9\-\_]+$')

class TestAdminForm(forms.ModelForm):
    hrname = forms.RegexField(
            label="Human Readable File Name", \
            regex=FNAME_EXP, \
            help_text="""Allowed only latin alphabet
                    (upper and lower cases), 
                    underscore and minus
                    characters. PLEASE, DO NOT INCLUDE
                    EXTENSION OF THE FILE.
                    Sample: test-this-file""", \
                    required=False)

    class Meta:
            model = Test

Sample admin.py for Test model:

class TestAdmin(admin.ModelAdmin):
    form = TestAdminForm

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

#

Please login first before commenting.