简体   繁体   中英

Linking a Cloudinary image upload to a Django model field

I've read through the Cloudinary Django docs and many StackOverflow questions and I'm still struggling with this basic problem. I want to upload an image as part of a data migration to a Cloudinary model field (of class CloudinaryField )

My model is defined in the following way:

# 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)

This model works fine, and I can upload an image via the admin without problems, and access it in my template.

I want to write a data migration so that I can upload many images to this model. My non-functioning migration is structured like so:

# 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()

I know that if I use cloudinary.uploader.upload("image.png") I get back something like this:

{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'}

I cannot figure out if relating the uploaded file to the model field is possible, using Cloudinary. All of the docs (and example code) do not show how to relate the uploaded response to a model field. There are examples that use a webform, but I'd prefer to avoid this if possible.

Try to use the following:

user.logo = cloudinary.uploader.upload_resource("https://url/to/logo/logo.png")

this should do the trick.

I contacted Cloudinary support, linked to this question and their answer was as follows:

Did you read thoroughly the documentation? Specifically the Python models topic is discussed here: http://cloudinary.com/documentation/django_image_upload#django_forms_and_models

My conclusion is that Cloudinary does not support the functionality I desire which surprises me as it seems quite basic.

So, I guess I can make a form, fake a request with the data in it so that I can upload a file to associate it with a model. This seems a but crazy but I can't see what the alternative is.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM