【问题标题】:Set default image to CloudinaryField in Model将默认图像设置为模型中的 CloudinaryField
【发布时间】:2020-07-09 04:14:00
【问题描述】:

我最近开始使用 Cloudinary 进行媒体存储。
我有一个带有图像和封面图像字段的 Profile 模型

没有 Cloudinary

​​>

在更改为云媒体存储之前,模型如下所示:

class Profile(models.Model):
    user = models.OneToOneField(User, related_name='profile', on_delete=models.CASCADE)

    # setup without Cloudinary
    image = models.ImageField(default='profile_image/default.jpg', upload_to='profile_image', blank=False)
    cover_image = models.ImageField(default='cover_image/default.jpg', upload_to='cover_image', blank=False)

它允许我为两个字段设置默认图像。

使用 Cloudinary

​​>

现在,添加 Cloudinary 后,它看起来像这样:

class Profile(models.Model):
    user = models.OneToOneField(User, related_name='profile', on_delete=models.CASCADE)

    # setup with Cloudinary
    image = CloudinaryField('image')
    cover_image = CloudinaryField('cover_image')

我希望能够为这两个字段设置默认图像。

这里是相关库的版本

Django==2.1.5
cloudinary==1.17.0
django-cloudinary-storage==0.2.3
olefile==0.46
cloudinary-cli==0.3.4

【问题讨论】:

    标签: django cloudinary


    【解决方案1】:

    Cloudinary 现在支持在请求的图像不存在时提供默认图像。

    假设您希望在页面中显示默认图像,我对您是否可以从模型中做到这一点了解有限,您可以在呈现该页面的视图中实现此功能例如

    CloudinaryImage("if_set_image.jpg").image(transformation=[
    'default_image': "default_image.png"
    ])
    

    有关更多信息,请阅读此articledocumentation

    鉴于您需要使用 cloudinary,您还可以考虑保留 django 提供的默认 ImageField(因此可以轻松设置默认选项)并使用 cloudinary.uploader.upload("my_image.jpg") 将图像上传到您的视图中的 cloudinary。

    【讨论】:

    • 感谢您的回答。很有帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-28
    • 2014-12-03
    • 1970-01-01
    • 2016-02-20
    • 1970-01-01
    相关资源
    最近更新 更多