目前我的views.py文件中有我的搜索功能json_search,如下所示:
def json_search(request):
query = request.GET.get('query')
api_key = locu_api
url = 'https://api.locu.com/v1_0/venue/search/?api_key=' + api_key
locality = query.replace(' ', '%20')
final_url = url + "&locality=" + locality + "&category=restaurant"
json_obj = urllib2.urlopen(final_url)
data = json.load(json_obj)
json_data = {}
return HttpResponse(json.dumps(data), content_type='application/json')
我目前通过主页上的表单使用以下网址调用它:
urlpatterns = patterns(
"",
url(r"^$", TemplateView.as_view(template_name="homepage.html"), name="home"),
url(r"^admin/", include(admin.site.urls)),
url(r"^account/", include("account.urls")),
url(r"^loc_search/$", 'project_name.views.json_search', name="search"),
)
我要做的是填写一个表格,其中包含字段名称:和phone:在api的json中我目前已经设置了表格:
<body>
<table data-toggle="table" data-url="{% url 'search' %}" data-cache="false" data-height="299">
<thead>
<tr>
<th data-field="id">Item ID</th>
<th data-field="name">Name</th>
<th data-field="phone">Phone</th>
</tr>
</thead>
我知道目前它只是返回HttpResponse并转储json文件,所以我得到一个像这样的空白html页面:
{"meta": {"limit": 25, "cache-expiry": 3600}, "objects": [{"name": "Pizza Hut delivery", "locality": "Norwich", "website_url": null, "cuisines": [], "region": "Norfolk", "long": 1.27727303158181, "phone": "01603 488900", "postal_code": null, "categories": ["other", "restaurant"], "has_menu": false, "country": "United Kingdom", "lat": 52.6564553358682, "id": "00388fe53e4c9f5e897d", "street_address": null, "resource_uri": "/v1_0/venue/00388fe53e4c9f5e897d/"}, {"name": "Thai Lanna", "locality": "Norwich", "website_url": "http://www.thailannanorwich.co.uk", "cuisines": [], "region": "Norfolk", "long": 1.2788060400004, "phone": "01603 625087", "postal_code": "NR2 1AQ", "categories": ["other", "restaurant"], "has_menu": true, "country": "United Kingdom", "lat": 52.6273547550005, "id": "0452369b7789e15bb624", "street_address": "24 Bridewell Alley", "resource_uri": "/v1
我只是想知道我是如何通过json数据的,以便我可以将搜索范围缩小到我想要的字段,我已经尝试使用rendor_to_response以及JsonResponse但我仍然坚持如何去做这个现在。我觉得我必须改变我的搜索功能,但我不知道如何。
已经停留了一段时间,所以任何帮助都会非常感激。
答案 0 :(得分:7)
最后设法使其工作我必须在我的views.py。中导入:
from django.shortcuts import render
然后我能够改变我的功能以满足将对象数据解析到我的模板,如下所示:
def json_search(request):
query = request.GET.get('query')
api_key = locu_api
url = 'https://api.locu.com/v1_0/venue/search/?api_key=' + api_key
locality = query.replace(' ', '%20')
final_url = url + "&locality=" + locality + "&category=restaurant"
json_obj = urllib2.urlopen(final_url)
decoded_data = json.load(json_obj)
return render(request, 'loc_search.html',
{'objects': decoded_data['objects']})
然后能够在我的表单提交后调用它:
<ul>
{% for obj in objects %}
<li>{{ obj.name }} - {{ obj.locality }}</li>
{% endfor %}
</ul>
给出理想的结果:)
希望任何有类似问题的人都能找到这个有用的