在 Django 模板中迭代 JSON

Noo*_*tor 5 iteration django json for-loop django-templates

我有一个 json 来自变量 ( AllUsers)中以下格式的视图:

{
  "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
}
Run Code Online (Sandbox Code Playgroud)

我需要在我的模板中遍历这个 JSON 并以下面的格式打印。所以理想情况下,我的循环应该在这种情况下运行 2 次。

name : aaa
name : aaa2
Run Code Online (Sandbox Code Playgroud)

我试过 :

{% for myusers in AllUsers %}
       name : {{ user.fname}}
{% end for%}
Run Code Online (Sandbox Code Playgroud)

{%with myusers=AllUsers.user%}
{% for user in myusers %}
name : {{ user.fname}}  
{% endfor %}
{% endwith %}
Run Code Online (Sandbox Code Playgroud)

但是它们都不起作用,因为循环甚至一次都没有迭代。在我读过的一个 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)
Run Code Online (Sandbox Code Playgroud)

我在迭代中哪里出错了?请帮忙..

ily*_*yew 5

解决方案比我想象的要容易得多:

假设您有一些类似于 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
    }
Run Code Online (Sandbox Code Playgroud)

(以上方案中的所有值均作为示例给出)

而且您知道要正确获得此响应,您的帖子正文中需要下一个变量:

{
"id": "",
"pass_code": "",
"search_for": "",
}
Run Code Online (Sandbox Code Playgroud)

接下来,您需要将带有所需值的 POST 请求发送到 API 服务器:

首先,您需要安装必要的组件(来自您的 virtualenv):

pip install requests[security]
Run Code Online (Sandbox Code Playgroud)

需要 [security] 标志才能成功响应 HTTPS

视图.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)
Run Code Online (Sandbox Code Playgroud)

你的模板.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>
Run Code Online (Sandbox Code Playgroud)

就是这样!祝你工作愉快!如果你乱搞,你可以事件获取这个请求的标头;-)