slug filename

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

importosdefslug_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" """returnlambdai,f:os.path.join(path,u''.join((i.slug,os.path.splitext(f)[1])))