Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 579
djq Avatar asked Oct 07 '15 22:10

djq


People also ask

How do I upload pictures to Cloudinary?

On the settings page, click on the upload tab, and scroll down to the upload presets section . Click on the bold text that says Enable unsigned uploading, this allows users to upload images and other assets into your Cloudinary account without pre-signing the upload request.


1 Answers

Try to use the following:

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

this should do the trick.

like image 97
Nadav Ofir Avatar answered Sep 28 '22 11:09

Nadav Ofir