【问题标题】:Can not print specifict values from an api response dictionnary (Dango)无法从 api 响应字典 (Dango) 打印特定值
【发布时间】:2021-02-25 16:32:25
【问题描述】:

我不熟悉 Django 和 API,我为此苦苦挣扎了好几天。 这是我的 views.py 文件:

import requests
import os
from pprint import pprint
from django.views.generic import TemplateView
import json
from django.http import JsonResponse, HttpResponse
from django.shortcuts import render

def index(request):


query_url = "https://api.blockcypher.com/v1/btc/main"
params = {
    "state": "open",
}
headers = {
    }
result = requests.get(query_url, headers=headers, params=params)
json_data = result.json()
data = json.dumps(json_data, sort_keys=True, indent=4)
t = json.loads(data)
print(type(data))
print(type(t))
context = {
    "t": t,
}
return render(request, "navbar/navbar.html", context)

这是 index.html :

    {% load static %}
<!DOCTYPE html>
    <html>
        <head>
            <title>Blockchain Explorer</title>
            <meta charset="utf-8"> 
            
        </head>

        <body >
            
            <div class="API-response">
                {{ t }}
             </div> 
        </body>
    </html> 

但是当我尝试做例如:

{{ t["height"] }}

我收到一个错误:(TemplateSyntaxError at / 无法解析余数:'["height"]' from 't["height"]')

如果这是一个愚蠢的问题,请帮助我并原谅我,我仍然是这个框架的初学者

【问题讨论】:

  • 试试{{ t.height }},属性访问、键查找和索引查找都在Django模板中使用.进行

标签: python html django dictionary


【解决方案1】:

您可以在模板中使用. 访问属性。看看访问方法调用documentation。您可以尝试使用t.height访问。

【讨论】:

    【解决方案2】:

    更明确地说明您的问题 例如,您的 t = items 是否

    在 Views.py 中 ... 上下文 = { “项目”:项目, } 返回渲染(请求,“navbar/navbar.html”,上下文)

    在前端模块中 ...

    {% for item in items %}
       <div class="API-response">
           {{ item }}
       </div>
    {% endfor %}
    

    所以我没有足够的数据来解决您的问题,以便更有效,但请尝试并提供反馈。谢谢

    【讨论】:

      猜你喜欢
      • 2021-06-01
      • 2017-07-19
      • 2020-09-29
      • 2019-04-10
      • 1970-01-01
      • 2022-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多