Created
May 6, 2012 18:55
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
+1 :)
Thanks!
Thanks ❤️
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you 👍