add image in an ImageField from image url with django

We have a model with one field:
#models.py


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
= 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.

No comments:

Post a Comment