Login

slug filename

Author:
willhardy
Posted:
July 16, 2009
Language:
Python
Version:
1.0
Tags:
upload_to
Score:
1 (after 1 ratings)

A one-liner that I use all the time: Set upload_to to something based on the slug and the filename's extension.

Just add this function to the top of your models and use it like this: image = models.FileField(upload_to=slug_filename('people'))

and the upload_to path will end up like this for eg myfile.jpg: people/this-is-the-slug.jpg

Enjoy!

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import os

def slug_filename(path):
    """ Returns a callable that can set upload_to to 'path/slug.ext'
        i is a (model) instance (with a field called 'slug'), f is a filename.

        >>> upload_to = slug_filename(u"/my/path/")
        >>> test_model_instance = type("",(),dict(slug=u"slugy"))()
        >>> upload_to(test_model_instance, u"myfilename.jpg")
        u"/my/path/slugy.jpg"
    """
    return lambda i,f: os.path.join(path, u''.join((i.slug, os.path.splitext(f)[1])))

More like this

  1. Use the primary key in FileField and ImageField filenames by exogen 6 years, 5 months ago
  2. Database file storage by powerfox 6 years, 1 month ago
  3. Unique naming for file uploads by mindcruzer 2 years, 6 months ago
  4. Updated FileField / ImageField with a delete checkbox by tomZ 7 years ago
  5. UnicodeReprMixIn by ashcrow 6 years, 2 months ago

Comments

Please login first before commenting.