2017-10-13 58 views
0

我正在尝试设置Cloudinary的上传控件,并在我的模型上将生成的Cloudinary对象保存到我的CloudinaryField()。 Cloudinary的sample project只显示如何使用{{form}}上传图像。Django - 通过上传控件保存Cloudinary对象

当我使用小部件上传时,我收到了一本字典,但在文档中我找不到任何可以保存它的地方。

+0

“字典”,你的意思是标识符字符串是生成的隐藏输入字段的值,或POST请求返回的JSON响应? –

+0

这是由POST请求返回给Cloudinary的一组值。我想这是JSON,但是我直接将它发送到后端,并且Python似乎将其识别为字典。也许我跳了一步? –

回答

1

上传小部件可以选择包含通知URL,并且可以在您的上传预设设置中进行配置。此通知网址将返回可用于保存图像模型的服务器端点响应。

要从上传响应中生成必需的CloudinaryField,可以使用CloudinaryResource对象。

from cloudinary import CloudinaryResource 

. . . 

json_response = { "public_id": "test", "type": "upload", . . . } 

# Populate a CloudinaryResource object using the upload response 
result = CloudinaryResource(public_id=json_response['public_id'], type=json_response['type'], resource_type=json_response['resource_type'], version=json_response['version'], format=json_response['format']) 

str_result = result.get_prep_value() # returns a CloudinaryField string e.g. "image/upload/v123456789/test.png" 

# Save the result 
p = Photo(title="title",image=str_result) 
p.save() # save result in database