Created
April 9, 2018 13:58
-
-
Save deniskrumko/bdc90ef4ca2f5a03f0458962cf8de487 to your computer and use it in GitHub Desktop.
Save image from URL to ImageField
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.base import ContentFile | |
from urllib.parse import urlparse | |
from urllib.request import urlopen | |
# Example URL | |
image_url = 'images.com/image.png' | |
# `obj` has `image` field | |
sample_obj = SampleObject.objects.first() | |
# Totally works for Django 1.10 and Python 3.6.4 | |
name = urlparse(self.icon_url).path.split('/')[-1] | |
content = ContentFile(urlopen(self.icon_url).read()) | |
sample_obj.image.save(name, content, save=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment