Login

Save image in field

Author:
grillermo
Posted:
January 8, 2012
Language:
Python
Version:
1.3
Tags:
image field save file
Score:
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)

More like this

  1. Database file storage by powerfox 6 years, 2 months ago
  2. save image from url to django ImageField by kriwil 3 years, 5 months ago
  3. Function to create resized versions of an image from a URL and saving it to a local path by obeattie 8 years, 1 month ago
  4. Simple Plone Migration by msm-art 7 years, 3 months ago
  5. Download an image using requests, resize it using PIL, and save it to a model ImageField. by stewx 1 month ago

Comments

Please login first before commenting.