django - 使用 Django/JavaScript 在 HTML 表中渲染 JSON
问题描述
朋友,我需要你的帮助!
我是 Python / Django 的新手,我正在用我从日常学习中获得的知识来做这个项目。
我的views.py 中有一个与API 通信并以Json 形式返回结果的函数。结果基本上是这样的:
[
{
"_id": "5d6f28ec02523e0012a4eae6",
"pass": false,
"renderSatisfaction": false,
"botTimeOut": false,
"ignore": false,
"exit": false,
"errorslog": [],
"chaterroslog": [],
"Historic": [],
"userID": "5b43b8a48b769470363b58909a9049",
"user_key": "ABCD",
"username": "Igor Miranda",
"Created_at": "2019-09-04T03: 01: 00.716Z",
"__v": 0
}
{
"_id": "5d6f291d55d3f500402d338e",
"pass": false,
"renderSatisfaction": false,
"botTimeOut": false,
"ignore": false,
"exit": false,
"errorslog": [],
"chaterroslog": [],
"Historic": [],
"userID": "577a55a043aab2a6aa78586b2520392",
"user_key": "ABCD",
"username": "Igor Miranda",
"Created_at": "2019-09-04T03: 01: 49.484Z",
"__v": 0
}
]
我需要使用 Django 在 HTML 页面中的表中呈现此结果,其中我有字段“用户名”、“用户名键”和“历史记录”的结果。
我在 StackOverFlow 上阅读了很多主题,但我仍然无法解决我的需求。
遵循我的views.py、ConsummirApi.html 文件和页面上的结果。
视图.py
def ConsumirApi(request):
url = 'http://urlapi.test.com.br'
body = {"start": "2019-09-04 19:30:00", "end": "2019-09-04 23:59:59"}
response = orders.post (url, auth = HTTPBasicAuth ('123456', 'password1234'),
headers = {'Content-Type': 'application / json'}, json = body)
result = json.loads (response.content)
output_result = [{k: v for k, v in x.items () if k in ["History", "user_name", "user_key"]} for x in result]
drop_falsey = lambda path, key, value: bool (value)
clean = remap (exit_ result, visit = drop_falsey)
final_result = json.dumps (clean, indent = 4, sort_keys = True)
return TemplateResponse (request, 'ConsumirApi.html', {"final_result": final_result})
ConsumirApi.html
<table id = "test_table" class = "display table with table border table with table border" border = "1" cellpacing = "0" width = "100%">
<thead>
<tr>
<th> user_name </th>
<th> user_key </th>
<th> History </th>
</tr>
</thead>
</table>
<script type = "text / javascript">
$ (document) .ready (function () {
var json = {{response.content | safe }}
$ ('# test_table'). DataTable ({
final result: json.final_result, // get the data array of the object
"columns": [
{"final_result": "user_key"},
{"final_result": "username"},
{"final_result": "History"}]
});
});
</script>
页面结果的图像,未创建表。 有人可以帮我确定我哪里出错了或者有什么遗漏吗?某些人在models.py文件中使用函数的一些项目,但我在这个文件中什么都没有,真的有必要在里面有什么吗?
解决方案
你可以试试这个,那是你通过的字典的名字
var json = {{final_result | safe }}
推荐阅读
- python - 如何通过python中的管道访问程序的输出
- docker-compose - 如何将用户名和密码传递给私有 Docker 注册表以进行“htpasswd”身份验证
- android - 在设备上使用 nativescript angular 6 将数据从我的应用程序发布到本地 api 时出现问题
- java - 使用反射从隐藏的 AOSP 类中获取私有字段
- javascript - React,this.props 没有定义
- java - 程序类型已经存在:javax.inject.Named + transformDexArchiveWithExternalLibsDexMergerForDebug FAILED
- javascript - sequelize.query() 抛出未处理的拒绝
- javascript - 错误 TS2554:预期 3-4 个参数,但得到 5
- python - 仅将月份从“jan”更改为 1,“feb”更改为 2,“mar”更改为 3...“dec”更改为 12
- flutter - Flutter 新的 Web 项目未显示在 Visual Studio 命令面板中