Created
September 6, 2021 15:13
-
-
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
This file contains hidden or 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
| 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