gpt4 book ai didi

python - 迭代数据库对象并将它们渲染到模板

转载 作者:行者123 更新时间:2023-12-01 05:04:28 25 4
gpt4 key购买 nike

我正在尝试将一些数据提供给模板。这是尝试执行此操作的 View 片段:

   def get(self, request, *args, **kwargs):
user = User.objects.get(username=request.user.username)
beac_data = user.get_profile().owned_beacons.all()
for beacon in beac_data:
beacon_data_name = beacon.name
beacon_data_factory_id = beacon.factory_id
beacon_data_location = beacon.location
beacon_data_visible = beacon.visible
beacon_data_config_id = beacon.config_id
#more code here

return render(request, self.template_name, {
'form': self.form,
'location': location,
'beacon_data_name': beacon_data_name,
'beacon_data_factory_id': beacon_data_factory_id,
'beacon_data_location': beacon_data_location,
'beacon_data_visible': beacon_data_visible,
'beacon_data_config_id': beacon_data_config_id,
})

如图所示,我迭代数据库中的对象并在 html 文件中提供相关的模板标签:

           {{ beacon_data_name }}
{{ beacon_data_factory_id }}
{{ beacon_data_location }}
{{ beacon_data_visible }}
{{ beacon_data_config_id }}

模板标签可以工作,但它只呈现第一个对象的信息。为什么它不返回数据库中所有对象的所有数据?一些帮助将不胜感激。

最佳答案

在上下文中传递beac_data并在模板中迭代它:

def get(self, request, *args, **kwargs):
user = User.objects.get(username=request.user.username)
beac_data = user.get_profile().owned_beacons.all()

return render(request, self.template_name, {
'form': self.form,
'location': location,
'beac_data': beac_data
})

然后,在模板中:

{% for beacon in beac_date %}
{{ beacon.name }}
{{ beacon.factory_id }}
{{ beacon.location }}
{{ beacon.visible }}
{{ beacon.config_id }}
{% endfor %}

关于python - 迭代数据库对象并将它们渲染到模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25335819/

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