5

I'm trying to download an image file from a URL and then assign that image to a Django ImageField. I've followed the examples here and [here](

My model, in pertinent part, looks like this:

class Entity(models.Model):

     logo = models.ImageField(upload_to=_getLogoPath,null=True)

The _getLogoPath callback is pretty simple:

def _getLogoPath(self,filename):
    path = "logos/" + self.full_name
    return path

The code for fetching and saving the image file is also straightforward as part of a custom django-admin command that I plan on running as a regularly scheduled cron job:

...
img_url = "http://path.to.file/img.jpg"
img = urllib2.urlopen(img)
entity.logo.save(img_filename,img,True)
...

When I run this, I get this error:

AttributeError: addinfourl instance has no attribute 'chunks'

I also tried adding read() to the image but resulted in a similar error. I also tried writing the image to a temporary file and then trying to upload that, but I get the same error.

Community
  • 1
  • 1
tchaymore
  • 3,728
  • 13
  • 55
  • 86

1 Answers1

7

If you read the docs you will see that the second argument to entity.logo.save needs to be an instance of django.core.files.File

So to retrieve an image and then save it using the imagefield you would need to do the following.

from django.core.files import File

response = urllib2.urlopen("http://path.to.file/img.jpg")
with open('tmp_img', 'wb') as f:
    f.write(response.read())

with open('tmp_img', 'r') as f:
    image_file = File(f) 
    entity.logo.save(img_filename, img_file, True)
os.remove('tmp_img')

The object you receive back from the call to urlopen is not the image itself. It's read method will return the binary image data though.

aychedee
  • 24,871
  • 8
  • 79
  • 83
  • 1
    You can use `from django.core.files.temp import NamedTemporaryFile` instead of `tmp_img`. See [this answer](http://stackoverflow.com/questions/1393202/django-add-image-in-an-imagefield-from-image-url/2141823#2141823). – Sergey Orshanskiy Dec 08 '13 at 06:59