[Answered ]-How to save an image from Google Places API to an ImageField in a Django app?

2👍

Try this:

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

city_image = NamedTemporaryFile(delete=True)
city_image.write(urllib2.urlopen(url).read())
city_image.flush()

created_city = City.objects.get_or_create(city_id=city_id)[0]
created_city.city_image = city_image 

0👍

After following the above answer and this tutorial

This worked for me to save a Google Places image to an ImageField:

First, prepare the URL to which HTTP Response is an image:

city_image_url = ('https://maps.googleapis.com/maps/api/place/photo'
        '?maxwidth=%s'
        '&photoreference=%s'
        '&key=%s') % (maxwidth, city_image_ref, GoogleKey) 

Second, retrieve that actual image and save it to a variable:

retrieved_image = requests.get(city_image_url)

Third, create a file locally and write the remote image’s content to it:

with open(city_names[i] + '.jpg', 'wb') as f:
                f.write(retrieved_image.content)

Fourth, open the file with the image inside it and convert it to a Django File:

reopen = open(city_names[i] + '.jpg', 'rb')
            django_file = File(reopen)

Fifth, create a model object and save the django file inside the ImageField like this:

created_city = City.objects.get_or_create(city_id=city_id)[0]
#save it to the ImageField -> args are: 1. the name of the file that is to be saved in MEDIA_ROOT path 2. The Django file itself 3. save instance
created_city.city_image.save(city_names[i] + '.jpg', django_file, save=True)
created_city.save()

Finally, these are the imports you need:

from django.core.files import File
import requests
👤Seif

Leave a comment