Django如何循环对象并在模板中显示变量
Posted
技术标签:
【中文标题】Django如何循环对象并在模板中显示变量【英文标题】:Django how to loop through objects and display variables in a template 【发布时间】:2017-11-26 13:48:29 【问题描述】:我正在使用 boto3 来显示关于我在 AWS 中的 s3 存储桶的各种数据。 我在views.py中有以下代码来显示s3页面:
class s3(TemplateView):
template_name = 'project/s3.html'
def get_context_data(self, **kwargs):
context = super(s3, self).get_context_data(**kwargs)
aws = boto3.resource('s3')
buckets = aws.buckets.all()
for bucket in buckets:
totalSize = 0
bucketName = bucket.name
createdAt = bucket.creation_date
fileBuckets = boto3.resource('s3').Bucket(bucketName)
for file in fileBuckets.objects.all():
totalSize += file.size
context['buckets'] = buckets
context['bucket'] = buckets
context['createdAt'] = createdAt
context['bucketName'] = bucketName
context['totalSize'] = totalSize
return context
我正在尝试在这样的模板中显示这些变量:
<div class="s3Items">
% for bucket in buckets %
<div class="s3Name">
<div id="left">
<h4 id='s3ItemName'> bucketName </h4>
</div>
<div id="right">
<ul id='s3ItemDesc'>
<li> createdAt </li>
<li> totalSize /4GB</li>
<li>
<button type="button" name="button" class='button delete'>Delete</button>
</li>
</ul>
</div>
</div>
% endfor %
但显然这行不通。如何遍历模板中的那些桶? 我还尝试了以下方法,但它工作但不完全,因为我无法获得每个存储桶中所有文件的总大小:
<div class="s3Items">
% for bucket in buckets %
<div class="s3Name">
<div id="left">
<h4 id='s3ItemName'> bucket.name </h4>
</div>
<div id="right">
<ul id='s3ItemDesc'>
<li> bucket.creation_date</li>
<li> ??? /4GB</li>
<li>
<button type="button" name="button" class='button delete'>Delete</button>
</li>
</ul>
</div>
</div>
% endfor %
我可以在模板中创建一个新循环吗?或者我应该在 python 文件中创建它并在模板中调用它?我怎样才能做到这一点? 谢谢
【问题讨论】:
【参考方案1】:您可以创建一个字典列表,然后可以在模板中迭代列表。
class s3(TemplateView):
template_name = 'project/s3.html'
def get_context_data(self, **kwargs):
context = super(s3, self).get_context_data(**kwargs)
data = []
aws = boto3.resource('s3')
buckets = aws.buckets.all()
for bucket in buckets:
bucket_data =
totalSize = 0
fileBuckets = boto3.resource('s3').Bucket(bucketName)
for file in fileBuckets.objects.all():
totalSize += file.size
bucket_data['bucketName'] = bucket.name
bucket_data['createdAt'] = bucket.createdAt
bucket_data['totalsize'] = totalSize
data.append(bucket_data)
context['buckets'] = data
return context
现在您可以在模板中迭代变量“buckets”。
<div class="s3Items">
% for bucket in buckets %
<div class="s3Name">
<div id="left">
<h4 id='s3ItemName'> bucket.bucketName </h4>
</div>
<div id="right">
<ul id='s3ItemDesc'>
<li> bucket.createdAt </li>
<li> bucket.totalsize /4GB</li>
<li>
<button type="button" name="button" class='button
delete'>Delete</button>
</li>
</ul>
</div>
</div>
% endfor %
【讨论】:
谢谢安妮塔,工作就像一个魅力!我没想过要创建字典。以上是关于Django如何循环对象并在模板中显示变量的主要内容,如果未能解决你的问题,请参考以下文章