Django: add image in an ImageField from image url

user166648 picture user166648 · Sep 8, 2009 · Viewed 59.3k times · Source

please excuse me for my ugly english ;-)

Imagine this very simple model :

class Photo(models.Model):
    image = models.ImageField('Label', upload_to='path/')

I would like to create a Photo from an image URL (i.e., not by hand in the django admin site).

I think that I need to do something like this :

from myapp.models import Photo
import urllib

img_url = 'http://www.site.com/image.jpg'
img = urllib.urlopen(img_url)
# Here I need to retrieve the image (as the same way that if I put it in an input from admin site)
photo = Photo.objects.create(image=image)

I hope that I've well explained the problem, if not tell me.

Thank you :)

Edit :

This may work but I don't know how to convert content to a django File :

from urlparse import urlparse
import urllib2
from django.core.files import File

photo = Photo()
img_url = 'http://i.ytimg.com/vi/GPpN5YUNDeI/default.jpg'
name = urlparse(img_url).path.split('/')[-1]
content = urllib2.urlopen(img_url).read()

# problem: content must be an instance of File
photo.image.save(name, content, save=True)

Answer

Chris Adams picture Chris Adams · Jan 26, 2010

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