Login

get and image object

Author:
grillermo
Posted:
March 1, 2012
Language:
Python
Version:
Not specified
Tags:
imagefield save file save url
Score:
0 (after 0 ratings)

I use this snippet to save images to my imagefields on django models. This uses the very awesome requests library, so install it first

pip install requests

You probably want to have this be done on a celery queu, if the image is big enough.

 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
27
28
29
30
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

More like this

  1. save image from url to django ImageField by kriwil 3 years, 5 months ago
  2. Save image in field by grillermo 3 years, 2 months ago
  3. Download an image using requests, resize it using PIL, and save it to a model ImageField. by stewx 1 week ago
  4. ImageField with per user folder by pigletto 7 years, 3 months ago
  5. Save an image to ImageField from URL by ekinertac 2 years, 5 months ago

Comments

Please login first before commenting.