我正在尝试使用以下格式的 API 中的数据。 count
可以不止一个 -
{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}
我正在使用以下方法来使用 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 %}
但是django似乎无法解析名称或id并给出错误 -
AttributeError: 'dict' object has no attribute 'city_name'
使用这些数据的正确方法是什么?我希望能够在我的模板中使用 json 的 results
中的所有数据,并使用 id 进行反向匹配并使用 id 转到下一个 View 。
最佳答案
我没有使用 requests json 但查看文档你应该将它用作字典作为常规 json 模块。
在您的代码中使用 'cities': data['results']
,然后在您的模板中使用 city.city_name
。
Django 模板使用点查找:当模板系统在变量名中遇到点时,它会尝试字典查找。
关于python - 在 Python Django 中使用 Json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34301138/