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'))
upload_to path will end up like this for eg
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))))
More like this
- Stuff by NixonDash 1 month, 1 week ago
- Add custom fields to the built-in Group model by jmoppel 3 months, 1 week ago
- Month / Year SelectDateWidget based on django SelectDateWidget by pierreben 6 months, 3 weeks ago
- Python Django CRUD Example Tutorial by tuts_station 7 months, 1 week ago
- Browser-native date input field by kytta 8 months, 3 weeks ago
Please login first before commenting.