我是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
访问。
更明确你的问题无论您的t =项目,例如
在Views.py…上下文= {"items"项目,}返回render(request, "navbar/navbar.html", context)
在前端模块…
{% for item in items %}
<div class="API-response">
{{ item }}
</div>
{% endfor %}
所以我没有足够的数据为您的问题,以便更有帮助,但尝试并给予反馈。由于