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


i'm building population code populate django model 'city' images google places api.

this model:

class city(models.model):     city_image = models.imagefield(blank=true, upload_to='city_pictures') 

i built api url returns photo:

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

google says response photo , tested on postman want this:

with urllib.request.urlopen(city_image_url) response:             city_image = response created_city = city.objects.get_or_create(city_id=city_id)[0] created_city.city_image = city_image  #plus other fields 

but receive error:

traceback (most recent call last): file "c:\users\bnbih\djangos\excurj_proj\population_script.py", line 68, in populate() file "c:\users\bnbih\djangos\excurj_proj\population_script.py", line 64, in populate created_city.save() file "c:\users\bnbih\appdata\local\programs\python\python36-32\lib\site-packages\django\db\models\base.py", line 796, in save force_update=force_update, update_fields=update_fields) file "c:\users\bnbih\appdata\local\programs\python\python36-32\lib\site-packages\django\db\models\base.py", line 824, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) file "c:\users\bnbih\appdata\local\programs\python\python36-32\lib\site-packages\django\db\models\base.py", line 886, in _save_table f in non_pks] file "c:\users\bnbih\appdata\local\programs\python\python36-32\lib\site-packages\django\db\models\base.py", line 886, in f in non_pks] file "c:\users\bnbih\appdata\local\programs\python\python36-32\lib\site-packages\django\db\models\fields\files.py", line 290, in pre_save if file , not file._committed: attributeerror: 'httpresponse' object has no attribute '_committed'

i'm using python 3 , django 1.10

try this:

from django.core.files import file 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  

Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -