Save image in field

 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. get and image object by grillermo 1 year, 3 months ago
  2. Database file storage by powerfox 4 years, 4 months ago
  3. Load static media from secure (SSL) static server (Context Processor) by ianreardon 3 years, 8 months ago
  4. HTTP authentication using your ModelBackend by dipankarsarkar 4 years, 7 months ago
  5. Reliably create a Django File using the contents of a URL by acdha 3 years, 4 months ago

Comments

(Forgotten your password?)