Created
March 23, 2012 17:15
-
-
Save anderser/2172888 to your computer and use it in GitHub Desktop.
Save image locally from submitted url in field image_url in Django model
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
from django.core.files.temp import NamedTemporaryFile | |
def save_image_from_url(self): | |
""" | |
Save remote images from url to image field. | |
Requires python-requests | |
""" | |
r = requests.get(self.image_url) | |
if r.status_code == 200: | |
img_temp = NamedTemporaryFile(delete=True) | |
img_temp.write(r.content) | |
img_temp.flush() | |
try: | |
self.image.save(os.path.basename(self.image_url), File(img_temp), save=True) | |
except: | |
print "Failed downloading image from ", self.image_url | |
return False | |
else: | |
return True | |
else: | |
return False |
Thanks
Thanks
Thanks
thank you
Thank you!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks!