def save_image_in_field(modelfield, url='',relativefile='',filename=None):
''' Takes a model field of that model and a optional url or a filename
and saves the image to that field.
The url must be absolute
The filename is relative to the firsr static dir, using Unix style slashes /
The field must be a DjangoImageField'''
if url and relativefile:
raise UserWarning('Function save_image_in_field expects a URL or a Filename not both.')
if not filename:
filename = url.split('/')[-1]
if url:
r = requests.get(url)
data = r.content
if relativefile:
r = open(os.path.join(settings.MEDIA_ROOT,filename),'rb')
data = r.read()
img_temp = NamedTemporaryFile(delete=True)
img_temp.write(data)
img_temp.flush()
modelfield.save(filename, File(img_temp), save=True)
Comments