Monday, August 3, 2009

Loading Django models.ImageField via a URL

The Django models.ImageField class is an easy way to store images in Django. However, for me it was unclear what to do if the user just has a URL. In my experience this is a common case. If you are building a website that aggregates content from other places and you are allowed to host the image content you are aggregating then it is cumbersome for a user to save a file to their local system and then upload it. It would be much easier if it was possible to use a URL to import this information.

Here is how to do that via the Django shell:

url = "http://media.buffalonews.com/smedia/2009/07/20/07/646-0720homelife.standalone.prod_affiliate.50.JPG";

import os
original_filename = os.path.basename(url)
fp = urllib.urlopen(url)
imgstr = cStringIO.StringIO(fp.read())
storage = S3Storage()
img = My_Image()
path = S3Storage.save(storage, original_filename, ContentFile(imgstr.getvalue()))
import Image
pilimg = Image.open(imgstr)
img.image = path
img.width = pilimg.size[0]
img.height = pilimg.size[1]
img.save()


I am using the S3Storage library to store my images.

No comments:

Post a Comment