【问题标题】:How to save CloudinaryField in a folder named by the user如何将 CloudinaryField 保存在用户命名的文件夹中
【发布时间】:2022-01-27 13:10:06
【问题描述】:

我正在尝试在我的models.py 中使用CloudinaryField 将图像上传到cloudinary。 我希望将图像上传到以这种格式命名的 cloudinary 文件夹:users/<username>/pictures/profile。 到目前为止,我知道我可以设置字段的folderpublic_id,但我不能动态命名它。例如,我可以在upload_to 中传递一个函数,在ImageField 中键入一个函数,以便在我想要的任何地方创建图像。有没有办法用CloudinaryField 做到这一点? 提前谢谢!

【问题讨论】:

标签: python django django-rest-framework django-views cloudinary


【解决方案1】:

在使用CloudinaryField时,它可以接受Upload API documentation中定义的参数。文件夹名称(或前缀)可以提供为 folder=some/target/foldername,同时使用 use_filename=Trueunique_filename=False将设置 public_id 以使用资产的文件名。否则,使用动态值也可以设置为public_id=some-dynamic-custom-value

例如:

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

【讨论】:

  • 试图以这种方式进行设置,但出现以下错误:public_id (users/<django.db.models.fields.CharField>/pictures/profile/) is invalid. 似乎我正在尝试使用尚不存在的字段......
  • 可以设置public_id为asset的文件名(即末尾没有/,支持文件名和扩展名)
【解决方案2】:

基于this question(建议的答案无效),我能够提出的唯一解决方案是像这样覆盖pre_save

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)

我不知道这是否是一个好的解决方案,但它是一个有效的解决方案......

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-14
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    • 2010-10-25
    • 2022-08-21
    • 2011-07-01
    • 2012-06-18
    相关资源
    最近更新 更多