Login

slug filename

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

Comments

Please login first before commenting.