Login

Save image in field

Author:
grillermo
Posted:
January 8, 2012
Language:
Python
Version:
1.3
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. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.