我有一个 json 来自变量( AllUsers
)中以下格式的 View :
{
"msg": "data found.",
"user": [
{
"fname": "aaa",
"lname": "aaa",
"add": "add1",
"city": "city1",
},
{
"fname": "aaa2",
"lname": "aaa2",
"add": "add2",
"city": "city2",
}
],
"data_status": "active",
"error": false
}
我需要在我的模板中遍历这个 JSON 并以下面的格式打印。所以理想情况下,我的循环应该在这种情况下运行 2 次。
name : aaa
name : aaa2
我试过 :
{% for myusers in AllUsers %}
name : {{ user.fname}}
{% end for%}
和
{%with myusers=AllUsers.user%}
{% for user in myusers %}
name : {{ user.fname}}
{% endfor %}
{% endwith %}
但是它们都不起作用,因为循环甚至一次都没有迭代。在我读过的一个 SO 线程中......你不应该“将它转换为 JSON”......但这不在我手中......我只是得到了 JSON。
Views
看起来像这样:def somefucn(request):
data = {
"msg": "data found.",
"AllUsers": AllUser ## This is where the above JSON resides
"data_status": "active",
"error": false
}
return TemplateResponse(request, 'path/to/Template.html', data)
我在迭代中哪里出错了?请帮忙..
最佳答案
解决方案比我想象的要容易得多:
假设您有一些类似于 POST 请求的 JSON,其架构如下:
"success": true,
"users": [
{
"userId": "76735142",
"username": "user11_01",
"email": "test11@test.com",
"isTest": false,
"create_at": "2016-01-29T15:41:16.901Z",
"isBlocked": false
}
(以上方案中的所有值均作为示例给出)
而且您知道要正确获得此响应,您的帖子正文中需要下一个变量:
{
"id": "",
"pass_code": "",
"search_for": "",
}
接下来,您需要将带有所需值的 POST 请求发送到 API 服务器:
首先,您需要安装必要的组件(来自您的 virtualenv):
pip install requests[security]
需要 [security] 标志才能成功响应 HTTPS
VIEWS.PY
import requests
from django.shortcuts import render_to_response
def get_user(request):
args = {}
args.update(csrf(request))
post_data = {'id': '1234', 'pass_code': 'pass', 'search_for': '123456'}
response = requests.post('https://example.com/api/', data=post_data)
args['contents'] = response.json()
return render_to_response('your_templae.html', args)
你的模板。HTML
<html>
<head>
<title>testing JSON response</title>
</head>
<body>
<div>
{% for user in contents.users %}
{{ user.userId}}<br>
{{ user.username}}<br>
{% empty %}
Nothing found
{% endfor %}
</div>
</body>
</html>
就是这样!祝你工作愉快!
如果你乱搞,你可以事件获取这个请求的 header ;-)
关于json - 在 Django 模板中迭代 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32563952/