gpt4 book ai didi

python - Django 如何循环对象并在模板中显示变量

转载 作者:行者123 更新时间:2023-11-30 22:25:34 36 4
gpt4 key购买 nike

我正在使用 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 文件中创建它并在模板中调用它?我怎样才能做到这一点?谢谢

最佳答案

您可以创建字典列表,然后可以迭代模板中的列表。

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 %}

关于python - Django 如何循环对象并在模板中显示变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47496829/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com