- January 8, 2012
- image field save file
- 0 (after 0 ratings)
Small function that i use to save files to an imagefield, the file can be either an url or a file. This function has the following requirements. import requests from django.core.files import File from django.core.files.temp import NamedTemporaryFile from django.conf import settings
Get the awesome requests library: pip install requests This function uses MEDIA_ROOT to know the location of the static dir, you can change that chaging the static_dir variable.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
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)