Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save victoraguilarc/86d06e5f601080cda473306a4e54f66f to your computer and use it in GitHub Desktop.
Save victoraguilarc/86d06e5f601080cda473306a4e54f66f to your computer and use it in GitHub Desktop.
Django: Programmatically saving image from URL to FileField or ImageField http://twigstechtips.blogspot.com/2012/04/django-programmatically-saving-image.html
class Product(models.Model):
# other fields
image = models.FileField(storage = MogileFSStorage(), upload_to = 'product_images')
from django.core.files import File
from django.core.files.temp import NamedTemporaryFile
product = Product()
# set all your variables here
product.save()
# Save image
image_url = 'http://whatever.com/image.jpg'
img_temp = NamedTemporaryFile(delete = True)
img_temp.write(urlopen(image_url).read())
img_temp.flush()
product.image.save("image_%s" % product.pk, File(img_temp))
product.save()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment