Skip to content

Instantly share code, notes, and snippets.

@heykarimoff
Last active May 20, 2022 19:56
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 heykarimoff/21faa0a0d1e25a087d3804d153135a2c to your computer and use it in GitHub Desktop.
Save heykarimoff/21faa0a0d1e25a087d3804d153135a2c to your computer and use it in GitHub Desktop.
django model filefield random upload path
# helpers.py
@deconstructible
class RandomFileName(object):
def __init__(self, path):
self.path = os.path.join(path, "%s%s")
def __call__(self, _, filename):
# @note It's up to the validators to check if it's the correct file type in name or if one even exist.
extension = os.path.splitext(filename)[1]
return self.path % (uuid.uuid4(), extension)
# models.py
class Foo(models.Model):
image = models.ImageField(upload_to=RandomFileName('my_app/model'))
@ahmedsafadii
Copy link

@deconstructible
class RandomFileName(object):

def __init__(self, path):
    self.path = os.path.join(path, "%s%s")

def __call__(self, _, filename):
    extension = os.path.splitext(filename)[1]
    return self.path % (uuid.uuid1(), extension)

uuid1() more safe to protect from duplicate

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