-
-
Save walteranyika/956d53fa60ed993d0b88bab9c01548ef to your computer and use it in GitHub Desktop.
Enforce unique upload file names in Django
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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