Login

save image from url to django ImageField

Author:
kriwil
Posted:
November 1, 2011
Language:
Python
Version:
1.3
Score:
1 (after 3 ratings)

Saves image from a url into django's ImageField in a model. Uses requests library.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import requests

from django.core.files import File
from django.core.files.temp import NamedTemporaryFile


def save_image_from_url(model, url):
    r = requests.get(url)

    img_temp = NamedTemporaryFile(delete=True)
    img_temp.write(r.content)
    img_temp.flush()

    model.image.save("image.jpg", File(img_temp), save=True)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

fuxter (on November 1, 2011):

ImportError: No module named requests

вхат!?

#

fuxter (on November 1, 2011):

ImportError: No module named requests

what!?

#

eos87 (on October 13, 2012):

pip install requests

#

Please login first before commenting.