Skip to content

Instantly share code, notes, and snippets.

@anderser
Created March 23, 2012 17:15
Show Gist options
  • Save anderser/2172888 to your computer and use it in GitHub Desktop.
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
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
@marzique
Copy link

Thanks!

@pbeneteau
Copy link

Thanks

@pustovitserhiy
Copy link

Thanks

@codertjay
Copy link

Thanks

@jungleKo
Copy link

thank you

@trey
Copy link

trey commented Feb 20, 2023

Thank you!

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