简体   繁体   中英

How to save CloudinaryField in a folder named by the user

I am trying to upload an image to cloudinary with a CloudinaryField in my models.py . I want the image to be uploaded to a folder in cloudinary named in this format: users/<username>/pictures/profile . so far I leart I can set folder and public_id of the field, but I cannot name it dynamically. for example I can pass a function in upload_to key in ImageField to create the image wherever i want. is there any way to do this with CloudinaryField ?? thanks ahead!

In using the CloudinaryField , it can accept parameters as defined in the Upload API documentation . The folder name (or prefix) can be provided as folder=some/target/foldername , while using both use_filename=True and unique_filename=False will set the public_id to use the filename of the asset. Otherwise, using a dynamic value can also be set as public_id=some-dynamic-custom-value .

For example:

           image = CloudinaryField('image',
                        public_id='dynamicpublicid',
                        use_filename=True,
                        unique_filename=False,
                        folder='users/username/pictures/profile')

The only solution I was able to come up with, based on this question (which suggested answer did not work) is to override pre_save like so:

class CloudinaryField(CloudinaryField):
def upload_options(self, instance):
    return {
        'folder': "users/{0}/cats/{1}".format(instance.owner.username,instance.name),
        'public_id': 'profile',
        'overwrite': True,
        'resource_type': 'image',
        'quality': 'auto:eco',
    }
def pre_save(self, model_instance, add):
    self.options =  dict(list(self.options.items()) + list(self.upload_options(model_instance).items())) 
    super().pre_save(model_instance, add)

I don't know if it's a good solution, but it's a working one...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM