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.

1
  • Can you add the part of the code which throws the exception? Commented Nov 15, 2012 at 7:37

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

You can use from django.core.files.temp import NamedTemporaryFile instead of tmp_img. See this answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.