Skip to content

Instantly share code, notes, and snippets.

@timonweb
Created May 6, 2012 18:55
Show Gist options
  • Save timonweb/2623793 to your computer and use it in GitHub Desktop.
Save timonweb/2623793 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()
@KILLLATIV
Copy link

Thank you 👍

@misteio
Copy link

misteio commented Dec 8, 2020

+1 :)

@cristianfavaro
Copy link

Thanks!

@GorlikItsMe
Copy link

Thanks ❤️

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment