Skip to content

Instantly share code, notes, and snippets.

@DKbyo
Created September 6, 2021 15:13
Show Gist options
  • Select an option

  • Save DKbyo/474458d7faf8fc9ee3aecc6730665363 to your computer and use it in GitHub Desktop.

Select an option

Save DKbyo/474458d7faf8fc9ee3aecc6730665363 to your computer and use it in GitHub Desktop.
Simple example of django filefield with auto generated uuid as file name and certain folder
from django.utils.deconstruct import deconstructible
@deconstructible
class upload_to(object):
def __init__(self, sub_path):
self.path = sub_path
def __call__(self, instance, filename):
ext = filename.split('.')[-1]
if instance.uuid is None:
instance.uuid = uuid.uuid4
return f'{self.path}/{str(instance.uuid)}.{ext}'
class User(models.Model):
avatar = models.FileField(upload_to=upload_to('avatar'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment