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!
CodePudding user response:
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')
CodePudding user response:
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...