【问题标题】:Django render a DynamoDB JSON into a HTML tableDjango 将 DynamoDB JSON 渲染为 HTML 表
【发布时间】:2020-07-31 19:12:18
【问题描述】:

我尝试使用 Django 页面作为前端,使用一些 AWS DynamoDB 表作为后端。 为此,我使用 boto3 库,它正确地从表中获取数据,但我无法将数据解析为 HTML 表。 我在views.py中有以下内容

def history(request):
     itemsid = list()
     agents = list()
     dates = list()
     source = list()
     dynamodb_resource('dynamodb')
     history_table = dynamodb_resource.Table('name_of_the_table')
     all_items = history_table.scan()
     for p in all_items['Items']:
       itemsid.append((p['id'])),
       agents.append((p['agent'])),
       dates.append((p['date'])),
       source.append((p['source']))
    return render(request, 'history.html', {'itemsid':itemsid, 'agents':agents, 'dates':dates, 'source':source}

问题是我不知道如何编写 html 代码来显示包含以下行的表格:id、代理、日期和来源。

我在 history.html 中有以下内容

<table>
  {% for i in itemsid %}
  <tr>
    <td>{{ i }}</td>
    ...

但我不知道如何对其进行编码(如何循环)以显示以列表为源的表格。

关于如何使用 Django 和 Python 将具有以下格式的 Json 解析为 HTML 有什么想法吗?

来自 DynamoDB 的 JSON:

{
  'Items: [ {
    'id': '94f'
    'agent': 'aws'
    'date': '04/05
    'source'
    'case1'
  }, {
    'id': 'lk42'
      ...

非常感谢。我是 Django 和一般编程的新手,所以非常感谢任何帮助。

【问题讨论】:

  • 你有代表这些数据的模型吗?
  • 不,我没有,因为我没有映射数据库,我认为在这种情况下我不需要模型。我直接从 DynamoDB 以 json 格式接收数据。那我需要模型吗?,你建议使用中间数据库吗?谢谢!
  • 不,我只是在确认。我发布了一个答案:)

标签: python html json django amazon-dynamodb


【解决方案1】:

Django 允许您访问模板内的 Dictionary 元素。所以你可以做这样的事情......

查看:

def history(request):
     dynamodb_resource('dynamodb')
     history_table = dynamodb_resource.Table('name_of_the_table')
     all_items = history_table.scan()
     return render(request, 'history.html', { items: all_items['Items'] })

您的模板:

<table>
  {% for item in items %}
    <tr>
        <td>{{ item.id }}</td>
        <td>{{ item.agent }}</td>
        <td>{{ item.date }}</td>
        <td>{{ item.source }}</td>
    </tr>
  {% endfor %}
</table>

【讨论】:

    猜你喜欢
    • 2011-06-01
    • 1970-01-01
    • 2021-02-17
    • 1970-01-01
    • 2020-01-12
    • 2016-02-14
    • 2020-04-12
    • 1970-01-01
    • 2018-01-17
    相关资源
    最近更新 更多