Menu Close

How to programmatically saving image to Python Django ImageField?

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.

Posted in Python, Python Answers