Programmatically saving image to Django ImageField

I have some code that fetches an image off the web and stores it in a model. The important bits are:

from django.core.files import File  # you need this somewhere
import urllib


# The following actually resides in a method of my model

result = urllib.urlretrieve(image_url) # image_url is a URL to an image

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

self.save()

That’s a bit confusing because it’s pulled out of my model and a bit out of context, but the important parts are:

  • The image pulled from the web is not stored in the upload_to folder, it is instead stored as a tempfile by urllib.urlretrieve() and later discarded.
  • The ImageField.save() method takes a filename (the os.path.basename bit) and a django.core.files.File object.

Let me know if you have questions or need clarification.

Edit: for the sake of clarity, here is the model (minus any required import statements):

class CachedImage(models.Model):
    url = models.CharField(max_length=255, unique=True)
    photo = models.ImageField(upload_to=photo_path, blank=True)

    def cache(self):
        """Store image locally if we have a URL"""

        if self.url and not self.photo:
            result = urllib.urlretrieve(self.url)
            self.photo.save(
                    os.path.basename(self.url),
                    File(open(result[0], 'rb'))
                    )
            self.save()

Leave a Comment