Skip to content

Instantly share code, notes, and snippets.

@shihweilo
Last active September 8, 2020 09:25
Show Gist options
  • Save shihweilo/699dc69bacb5a4d89aa7e9e2aee3e809 to your computer and use it in GitHub Desktop.
Save shihweilo/699dc69bacb5a4d89aa7e9e2aee3e809 to your computer and use it in GitHub Desktop.
Django upload image from URL to ImageField
# reference: https://goodcode.io/articles/django-download-url-to-file-field/
from tempfile import TemporaryFile
from os.path import basename
from urllib.parse import urlsplit
from django.core.files import File
import requests
class Foo(models.Model):
cover_image = models.ImageField(null=True)
def set_cover_image_from_url(self, url):
# delete existing cover_image if available
if self.cover_image:
self.cover_image.delete()
with TemporaryFile() as tf:
r = requests.get(url, stream=True)
for chunk in r.iter_content(chunk_size=4096):
tf.write(chunk)
tf.seek(0)
self.cover_image.save(basename(urlsplit(url).path), File(tf))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment