在Python Django中使用Json
我正在尝试使用API中的数据,其格式如下。其中,在Python Django中使用Json,python,json,django,django-rest-framework,Python,Json,Django,Django Rest Framework,我正在尝试使用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 = reque
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)
{% for city in cities %}
<a href="{% url 'next_view_name' city.id %}"><p>{{city.city_name}}</p></a>
{% endfor %}
template.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)
{% for city in cities %}
<a href="{% url 'next_view_name' city.id %}"><p>{{city.city_name}}</p></a>
{% endfor %}
使用这些数据的正确方法是什么?我希望能够在我的模板中使用json的
结果中的所有数据,并使用id进行反向匹配,然后使用id转到下一个视图。我没有使用请求json,但查看文档时,您应该将其用作常规json模块的字典。
在您的代码中使用'cities':数据['results']
,然后在您的模板中使用city.city\u name
Django模板使用点查找:当模板系统在变量名中遇到点时,它会尝试字典查找。它看起来像是'city\u name'
是数据的属性。结果[0]
,而不是数据。city
。很抱歉,我无法测试请求.get(url).json()
,因此它可能需要是数据['results'][0]
你能给出一个例如数据的输出吗。city
你能编辑你的问题来发布你错误的完整堆栈跟踪吗?看起来像'cities':数据。city
应该是'cities':数据。结果
@JosepValls是的,对不起。现在就编辑它。但即使这样也会给出同样的错误AttributeError at/dict'对象没有属性“结果”
data['results']
怎么办?但那只会得到我的名字。身份证呢?每次我想要一个propertySorry时,我都必须运行几个语句,使用city['city\u name']
而不是city。city\u name
只会给我以下错误-无法解析剩余部分:“['city\u name']”来自“city['city\u name']
我检查过,在Django模板中,你似乎可以实际使用city.city\u name。你已经试过了吗?