Skip to content

Instantly share code, notes, and snippets.

@Verurteilt
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Verurteilt/8058fc2cb0482e5abf9a to your computer and use it in GitHub Desktop.
Save Verurteilt/8058fc2cb0482e5abf9a to your computer and use it in GitHub Desktop.
import uuid
import requests
from django.core.files.base import ContentFile
from django.db import models
from django.db.models.fields.files import ImageFileDescriptor, ImageFieldFile
class UrlImageFileDescriptor(ImageFileDescriptor):
def __init__(self, field):
super(UrlImageFileDescriptor, self).__init__(field)
def __set__(self, instance, value):
if not value:
return
if isinstance(value, str):
value = value.strip()
if len(value) < 1:
return
if value == self.__get__(instance):
return
# Fetch and store image
try:
response = requests.get(value, stream=True)
_file = ""
for chunk in response.iter_content():
_file+=chunk
headers = response.headers
if 'content_type' in headers:
content_type = "." + headers['content_type'].split('/')[1]
else:
content_type = "." + value.split('.')[-1]
name = str(uuid.uuid4()) + content_type
value = ContentFile(_file, name)
except Exception as e:
print e
pass
super(UrlImageFileDescriptor,self).__set__(instance, value)
class UrlImageField(models.ImageField):
descriptor_class = UrlImageFileDescriptor
class TryField(models.Model):
logo = UrlImageField(upload_to="victor")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment