Menu Close

How to add image in an ImageField from image URL with Python Django?

To add image in an ImageField from image URL with Python Django, we can use the NamedTemporaryFile class.

For instance, we write

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

to get the create a NamedTemporaryFile object.

Then we call write with the image result we get from urllib2.urlopen(url).read() where url is the image URL.

And then we call flush to put the file into img_temp.

Then we save img_temp as the file with

im.file.save(img_filename, File(img_temp))
Posted in Python, Python Answers