Download a remote image and save it to a Django model

Django Documentation is always good place to start

class ModelWithImage(models.Model):
    image = models.ImageField(
        upload_to='images',
    )

UPDATED

So this script works.

  • Loop over images to download
  • Download image
  • Save to temp file
  • Apply to model
  • Save model

.

import requests
import tempfile

from django.core import files

# List of images to download
image_urls = [
    'http://i.thegrindstone.com/wp-content/uploads/2013/01/how-to-get-awesome-back.jpg',
]

for image_url in image_urls:
    # Stream the image from the url
    response = requests.get(image_url, stream=True)

    # Was the request OK?
    if response.status_code != requests.codes.ok:
        # Nope, error handling, skip file etc etc etc
        continue
    
    # Get the filename from the url, used for saving later
    file_name = image_url.split("https://stackoverflow.com/")[-1]
    
    # Create a temporary file
    lf = tempfile.NamedTemporaryFile()

    # Read the streamed image in sections
    for block in response.iter_content(1024 * 8):
        
        # If no more file then stop
        if not block:
            break

        # Write image block to temporary file
        lf.write(block)

    # Create the model you want to save the image to
    image = Image()

    # Save the temporary image to the model#
    # This saves the model so be sure that it is valid
    image.image.save(file_name, files.File(lf))

Some reference links:

  1. requests – “HTTP for Humans”, I prefer this to urllib2
  2. tempfile – Save temporay file and not to disk
  3. Django filefield save

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)