Skip to content

Instantly share code, notes, and snippets.

@gameame
Created November 18, 2011 10:24
Show Gist options
  • Save gameame/1376105 to your computer and use it in GitHub Desktop.
Save gameame/1376105 to your computer and use it in GitHub Desktop.
Enforce unique upload file names in Django
def unique_filename(path):
"""
Enforce unique upload file names.
Usage:
class MyModel(models.Model):
file = ImageField(upload_to=unique_filename("path/to/upload/dir"))
"""
import os, base64, datetime
def _func(instance, filename):
name, ext = os.path.splitext(filename)
name = base64.urlsafe_b64encode(name.encode("utf-8") + str(datetime.datetime.now()))
return os.path.join(path, name + ext)
return _func
@LucaBazzea
Copy link

Very helpful, thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment