import requests #get it http://docs.python-requests.org/en/latest/index.html
def get_img_obj(url='',relativefile='',absolutefile=''):
''' Takes a url or a relative path to a file in the static dir and returns
an object suitable to be asigned in an imagefield = get_img_obj(url='url')'''
if url and relativefile:
raise UserWarning('Function save_image_in_field expects a URL or a Filename not both.')
if url:
r = requests.get(url)
data = r.content
if relativefile:
r = open(os.path.join(settings.STATICFILES_DIRS[0],relativefile),'rb')
data = r.read()
if absolutefile:
r = open(absolutefile,'rb')
data = r.read()
img_temp = NamedTemporaryFile(delete=True)
img_temp.write(data)
img_temp.flush()
return File(img_temp)
##### And you can use it like this:
## Asume that profile is some model and image is an imagefield of that model
profile.image.save('some name.jpg',get_img_obj('http://google.com/logo.jpg'))#url
profile.image.save('some name.jpg',get_img_obj(relativefile='images/logo.jpg'))# the file is on ~/django_project/static/image/logo.jpg
profile.image.save('some name.jpg',get_img_obj(absolutefile='~/userfile.jpg'))# you pass the full path to the file
Comments