Login

Human readable file names decorator

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