【问题标题】:How do I display my views output variable in my template in Django?如何在 Django 的模板中显示我的视图输出变量?
【发布时间】:2018-07-23 17:39:05
【问题描述】:

我有我的 Django views.py 函数:

def dsctbl2(request):
dynamodb=boto3.client('dynamodb', region_name='us-west-2')
response = dynamodb.scan(
TableName='User-Account')
 filtered = response['Items']
length = len(filtered)
a = []
for k in range(length):
  accnum = filtered[k]['AccountNum']['S']
  uid = filtered[k]['UserId']['S']
  f = {}
  f = dict(AccountNum=accnum,UserId=uid)
  a.append(f)
return (a)

上述函数从 dynamodb 表中过滤 UserId 和 Accountnumber 项。我需要在我的 html 模板中的表格行中显示“UserId”和“AccountNum”。

这是我的 html sn-p :

<div class="mytable">
   <table style="width:96%" class="table table-responsive">
     <thead id="head" class="mdb-color lighten-4">
                <tr>
                    <th></th>
                    <th class="th-lg">User ID</th>
                    <th class="th-lg">Account Number</th>
                </tr>
      </thead>

      <tbody>
              {% for r in rows %}
                <tr>
                    <th scope="row"></th>
                  <td>{{r.AccountNum}}</td>
                  <td>{{r.UserId}}</td>
               </tr>
               {% endfor %}
            </tbody>

        </table>

</div>

我在我的 html 代码中包含了块内容和结束块标签。我在这里做错了什么?我是 Django 的初学者。提前致谢

【问题讨论】:

  • 您需要将输出呈现到您的 html 文件中。 Ex return render_to_response(your.html', {"rows":a})

标签: python django django-templates django-views


【解决方案1】:

您需要将输出呈现到您的 html 文件中。

例如:

from django.shortcuts import render_to_response

def dsctbl2(request):
    dynamodb=boto3.client('dynamodb', region_name='us-west-2')
    response = dynamodb.scan(
    TableName='User-Account')
    filtered = response['Items']
    length = len(filtered)
    a = []
    for k in range(length):
      accnum = filtered[k]['AccountNum']['S']
      uid = filtered[k]['UserId']['S']
      f = {}
      f = dict(AccountNum=accnum,UserId=uid)
      a.append(f)
    return render_to_response('your.html', {"rows":a}) 

【讨论】:

  • 是的!现在页面出现了。我可以看到表格标题,但看不到内容。也许我的视图函数代码有一些问题。非常感谢 !美好的一天:)
  • 不客气,如果以上解决方案解决了您的问题,请采纳谢谢
  • 您应该使用render 而不是render_to_response,后者已被弃用。
  • @DanielRoseman;你说的对。我还在用旧版本:(
猜你喜欢
  • 1970-01-01
  • 2014-11-24
  • 1970-01-01
  • 2018-07-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多