Reputation: 859
I am trying to consume data from API which is in the following format. Where count
can be more than one -
{u'count': 1, u'previous': None, u'results': [{u'url': u'http://127.0.0.1:8000/offapp/cities/', u'city_name': u'Kolkata', u'id': 1}], u'next': None}
I am using the following method to consume json -
views.py
def employee(request):
data = requests.get('http://127.0.0.1:8000/offapp/cities/').json()
context = RequestContext(request, {
'cities': data.results,
})
return render_to_response('template.html', context)
template.py
{% for city in cities %}
<a href="{% url 'next_view_name' city.id %}"><p>{{city.city_name}}</p></a>
{% endfor %}
But django can't seem to resolve the name or id and gives the error -
AttributeError: 'dict' object has no attribute 'city_name'
What is the correct way to use this data? I want to be able to use all the data in results
of json in my template and use id to reverse match and go to the next view using id.
Upvotes: 2
Views: 860
Reputation: 5560
I have not used requests json but looking at the documentation you should be using it as a dictionary as the regular json module.
In your code use 'cities': data['results']
and then in your template use city.city_name
.
Django templates use dot lookups: when the template system encounters a dot in a variable name, it tries a dictionary lookup.
Upvotes: 1
Reputation: 91
It looks like 'city_name'
is a property of data.results[0]
, not data.city
. Sorry I can't test the requests.get(url).json()
, so it may need to be data['results'][0]
Upvotes: 0