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)

Combining what Chris Adams and Stan said and updating things to work on Python 3, if you install Requests you can do something like this:

from urllib.parse import urlparse
import requests
from django.core.files.base import ContentFile
from myapp.models import Photo

img_url = 'http://www.example.com/image.jpg'
name = urlparse(img_url).path.split('/')[-1]

photo = Photo() # set any other fields, but don't commit to DB (ie. don't save())

response = requests.get(img_url)
if response.status_code == 200:
    photo.image.save(name, ContentFile(response.content), save=True)

More relevant docs in Django's ContentFile documentation and Requests' file download example.

If you are using file uploading feature in your Django project, you must install Pillow first:

pip install pillow==2.6.1

Remember to set the url for media files in settings.py:

MEDIA_ROOT = 'media/'

Then, in your models.py, add the following image field:

userlogo = models.ImageField(upload_to="userlogo/", blank=True, null=True)

After writing this code, migrate the model using:

python manage.py makemigrations
python manage.py migrate

Now you can upload image files using the image field. The image files would get uploaded to YOUR_PROJECT_ROOT/media/userlogo directory. You dont need to create the 'userlogo' folder manually.

  • This doesn't answer the OP's question. He already has the image field set up and working. He needed to programmatically get the image content from an URL and save it to an ImageField. – Eduard Luca Jan 11 '16 at 22:43

from myapp.models import Photo
import urllib
from urlparse import urlparse
from django.core.files import File

img_url = 'http://www.site.com/image.jpg'

photo = Photo()    # set any other fields, but don't commit to DB (ie. don't save())
name = urlparse(img_url).path.split('/')[-1]
content = urllib.urlretrieve(img_url)

# See also: http://docs.djangoproject.com/en/dev/ref/files/file/
photo.image.save(name, File(open(content[0])), save=True)

  • Hi, thank you for helping me ;). The problem is (I quote the doc) : "Note that the content argument must be an instance of File or of a subclass of File." So do you have any solution to create File instance with your content ? – user166648 Sep 8 '09 at 14:29
  • Check the new edit; this should now be a working example (although I have not tested it) – pithyless Sep 9 '09 at 9:49
  • What about my model, where i have other fields aswell. Like url, etc, etc. If id do model.image.save(...). how do I save the other fields? They cant be null EDIT: woudl it be something like this? >>> car.photo.save('myphoto.jpg', contents, save=False) >>> car.save() – Harry Aug 27 '10 at 9:48
  • self.url??...what is self.url here?? – DeadDjangoDjoker May 29 '15 at 15:41
  • @DeadDjangoDjoker No idea, you'd have to ask the person who edited my answer. This answer is 5 years old at this point; I've reverted to the previous "working" solution for posterity, but honestly you're better off with Chris Adam's answer. – pithyless May 30 '15 at 18:13

I do it this way on Python 3, which should work with simple adaptations on Python 2. This is based on my knowledge that the files I’m retrieving are small. If yours aren’t, I’d probably recommend writing the response out to a file instead of buffering in memory.

BytesIO is needed because Django calls seek() on the file object, and urlopen responses don’t support seeking. You could pass the bytes object returned by read() to Django's ContentFile instead.

from io import BytesIO
from urllib.request import urlopen

from django.core.files import File


# url, filename, model_instance assumed to be provided
response = urlopen(url)
io = BytesIO(response.read())
model_instance.image_field.save(filename, File(io))

this is the right and working way

class Product(models.Model):
    upload_path = 'media/product'
    image = models.ImageField(upload_to=upload_path, null=True, blank=True)
    image_url = models.URLField(null=True, blank=True)

    def save(self, *args, **kwargs):
        if self.image_url:
            import urllib, os
            from urlparse import urlparse
            filename = urlparse(self.image_url).path.split('/')[-1]
            urllib.urlretrieve(self.image_url, os.path.join(file_save_dir, filename))
            self.image = os.path.join(upload_path, filename)
            self.image_url = ''
            super(Product, self).save()
  • 11
    That can't be the right way, you circumvent the whole file storage mechanism of the FielField and pay no respect to the storage api. – Andre Bossard Mar 21 '13 at 13:39

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))
  • 3
    what is the last line doing? what is the im object coming from? – priestc Jan 3 '14 at 1:27
  • 1
    @priestc: im was a bit terse - in that example, im was the model instance and file was the unimaginative name of a FileField/ImageField on that instance. The actual API docs here are what matter – that technique should work anywhere you have a Django File object bound to an object: docs.djangoproject.com/en/1.5/ref/files/file/… – Chris Adams Jan 3 '14 at 15:23
  • 23
    A temporary file is unnecessary. Using requests instead of urllib2 you can do: image_content = ContentFile(requests.get(url_image).content) and then obj.my_image.save("foo.jpg", image_content). – Stan Apr 16 '14 at 2:48
  • Stan: requests does simplify that but IIRC that one-liner would be a problem unless you called raise_for_status() first to avoid confusion with errors or incomplete responses – Chris Adams Apr 21 '14 at 20:55
  • It probably would be a good idea to modernize this since it was originally written in the Django 1.1/1.2-era. That said, I believe ContentFile still has the problem that it will load the entire file into memory so a nice optimization would be using iter_content with a reasonable chunk size. – Chris Adams Apr 21 '14 at 21:00

ImageField is just a string, a path relative to your MEDIA_ROOT setting. Just save the file (you might want to use PIL to check it is an image) and populate the field with its filename.

So it differs from your code in that you need to save the output of your urllib.urlopen to file (inside your media location), work out the path, save that to your model.

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.