Skip to content

Instantly share code, notes, and snippets.

@dchaplinsky
Created November 3, 2010 12:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dchaplinsky/661040 to your computer and use it in GitHub Desktop.
Save dchaplinsky/661040 to your computer and use it in GitHub Desktop.
Custom upload_to callback which using given names of fields to obtain access to storage and input data to create a slug
import os
from django.template.defaultfilters import slugify
try: # make it python2.4 compatible!
from hashlib import md5
except:
import md5
def picture_filename(path, field_name, field_to_slug = None):
def upload_to(instance, filename):
field = instance._meta.get_field(field_name)
if field_to_slug:
new_fname = slugify(getattr(instance, field_to_slug, ''))
if new_fname != '':
filename = u''.join((new_fname, os.path.splitext(filename)[1]))
m = md5()
m.update(filename)
filename = os.path.join(path, m.hexdigest()[:2], field.get_filename(filename))
if len(filename) > field.max_length:
basename, ext = os.path.splitext(filename)
# +4 to ensure, that _nnn added by storage backend to filename won't overcome field limit
basename = basename[:field.max_length - len(ext) + 4]
filename = u''.join((basename, ext))
return filename
return upload_to
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment