djq*_*djq 4 python django image-uploading python-2.7 cloudinary
我已经阅读了Cloudinary Django 文档和许多StackOverflow问题,但我仍然在解决这个基本问题。我想将图像作为数据迁移的一部分上传到Cloudinary模型字段(的类CloudinaryField)
我的模型通过以下方式定义:
# model definition
from cloudinary.models import CloudinaryField
from django.contrib.gis.db import models
class UserProfile(models.Model):
name = models.CharField(max_length=200)
logo = CloudinaryField(blank=True, null=True)
Run Code Online (Sandbox Code Playgroud)
这个模型运作良好,我可以顺利通过管理员上传图片,并在模板中访问它。
我想编写一个数据迁移,以便可以将许多图像上传到该模型。我无法正常运行的迁移的结构如下:
# migration file to upload logos
import cloudinary
# get all user instances
users = UserProfile.objects.all()
# loop through users, and update logo
for user in users:
user.logo = cloudinary.uploader.upload("https://url/to/logo/logo.png")
user.save()
Run Code Online (Sandbox Code Playgroud)
我知道如果使用,cloudinary.uploader.upload("image.png")我会得到如下信息:
{u'secure_url': u'https://res.cloudinary.com/mysite/image/upload/111/111.png', u'public_id': 111', u'format': u'png', u'url': u'http://res.cloudinary.com/mysite/image/upload/v1444253137/111.png', u'created_at': u'2015-10-07T21:25:37Z', u'tags': [], u'bytes': 7974, u'height': 35, u'width': 290, u'version': 1444253137, u'etag': u'aaa', u'original_filename': u'logo', u'signature': u'111', u'type': u'upload', u'resource_type': u'image'}
Run Code Online (Sandbox Code Playgroud)
我无法确定是否可以使用Cloudinary将上传的文件与模型字段相关联。所有文档(和示例代码)均未显示如何将上载的响应与模型字段相关联。有一些使用网络表单的示例,但我希望尽可能避免这种情况。
小智 5
尝试使用以下内容:
user.logo = cloudinary.uploader.upload_resource("https://url/to/logo/logo.png")
Run Code Online (Sandbox Code Playgroud)
这应该可以解决问题。