Skip to content

Instantly share code, notes, and snippets.

@walteranyika
Forked from gameame/gist:1376105
Created November 2, 2023 09:51
Show Gist options
  • Save walteranyika/956d53fa60ed993d0b88bab9c01548ef to your computer and use it in GitHub Desktop.
Save walteranyika/956d53fa60ed993d0b88bab9c01548ef 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment