Jun 15, 2011

Django: add image in an ImageField from image url

Today I had experience with django file downloads from an specified url into Django model FileField.
I'm writing content grabber from Flickr. I didn't find information about it and decided to write what I've discovered so far in example.

Stackoverflow helped me a bit. But answer proposed there had not worked.
So this is code example how to workout this issue:
because code worth a thousand words :)

We have a model with one field:

class Photo(models.Model):
    image = models.ImageField('Label', upload_to='path/')

We need to create a photo from image url and save it to the model's FileField.

#somewhere in views.py

# usually in header imports
from urlparse import urlparse 
import urllib2 
from django.core.files import File
  #add imprt of content file wrapper
from django.core.files.base import ContentFile
# somewhere: for e.g. in view handling the file operations
= Photo() img_url = 'http://i.ytimg.com/vi/GPpN5YUNDeI/default.jpg' name = urlparse(img_url).path.split('/')[-1]   #wrap your file content content = ContentFile(urllib2.urlopen(img_url).read())) photo.image.save(name, content, save=True)

In my project I used this in a bit another way.
First a user (site admin, for now) synchronizes with Flickr. He downloads into django model all photos data for flickr "username".
Than all this synched photos appear in a view, where user can choose what photos to download into main app model.
Than it passes chosen list to next view. It parses synched model and actually downloads photos to main App.
Finally it cleans up temporary Flickr sync model.

Maybe that is an ugly and bad way to do this. My excuses are to code less, because of using almost untouched plugin code. This feature, also, must be used 1 or 2 times in site production stage only.
So it is made for this purposes.

Maybe later I'll write an article on making Flickr content grabber for your Django site.
For now, thanks for reading and may The Code be with you!

Ideas, Suggestions? Please drop me a comment!