Django: add image in an ImageField from image url

I just created http://www.djangosnippets.org/snippets/1890/ for this same problem. The code is similar to pithyless’ answer above except it uses urllib2.urlopen because urllib.urlretrieve doesn’t perform any error handling by default so it’s easy to get the contents of a 404/500 page instead of what you needed. You can create callback function & custom URLOpener subclass but I found it easier just to create my own temp file like this:

from django.core.files import File
from django.core.files.temp import NamedTemporaryFile

img_temp = NamedTemporaryFile(delete=True)
img_temp.write(urllib2.urlopen(url).read())
img_temp.flush()

im.file.save(img_filename, File(img_temp))

Leave a Comment