Categories
Python Answers

How to programmatically saving image to Python Django ImageField?

Spread the love

To programmatically saving image to Python Django ImageField, we can call save with the path we want to save the file to.

For instance, we write

from django.core.files import File 
import urllib

result = urllib.urlretrieve(image_url)

self.photo.save(
    os.path.basename(self.url),
    File(open(result[0], 'rb'))
    )

self.save()

in a model class method.

We call save on the photo ImageField with the path to save to as the argument.

And we save the file that we opened from urllib.urlretrieve method by creating a File object from it.

We create the file by call open with the result[0] file with read permission.

Finally, we call self.save to save the model data.

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 *