json - 在 Django 模板中迭代 JSON

标签 json django for-loop django-templates iteration

我有一个 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/

相关文章:

django - 每次运行 django 代码时如何创建新的 postgreSQL 行以保存数据

c++ - 默认情况下不使用 std::next 的 Range-for 循环?

javascript - 如何在 JSFiddle 中使用 localhost URL 的 getJSON 返回键/值对?

javascript - Protractor 数据驱动 - 当我尝试打印 JSON 文件时显示 'undefined'

json - JSONP 可以扩展吗?在我的页面填满 &lt;script&gt; 标签之前,我可以发送多少个 JSONP 请求?

django - 在模板中获取用户组

具有 Django REST 框架的本地和 mod_wsgi 服务器之间的 Django JWT 身份验证行为不同

sql - 具有基于 ORDER BY 的 Limit/Rownum 的 Oracle JSON_ARRAYAGG

javascript - 如何使用替换创建 "bbcode"javascript

ios - 带后台循环的 for 循环,有完成吗?