Categories
Python Answers

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

Spread the love

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

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *