gpt4 book ai didi

python - 字典中的类 - Django 模板

转载 作者:太空宇宙 更新时间:2023-11-03 14:25:01 25 4
gpt4 key购买 nike

可能是一个简单的问题,但我已经搜索了一段时间,但无法找到如何循环遍历字典中的所有项目并调用模板内的类项目的答案

我尝试过使用自定义模板标签,但语法似乎与我想要的不符。

这是我的代码:

data = [[OrderedDict([('token', 'XXXXXXXXXXXXXXX'), ('devices', [['Christmas Lights', 'XXXXXXXXXX'], ['Gold Beedrom Lamp', 'XXXXXXXX']])])], [[['5', 'off', 124], ['6', 'off', 124], ['7', 'off', 100], ['8', 'off', 124]]]]

#Dictionary and Class assignment

class LightStatus:
def __init__(self,id):
self.id = id
self.state = None
self.bri = None
def add_data(self,id,state,bri):
self.id = id
self.state = state
self.bri = bri

AllLights = dict()
for i in data[1]:
for light in i:
id = light[0]
state = light[1]
bri = light[2]
AllLights[id] = LightStatus(id)
AllLights[id].add_data(id,state,bri)

我想在模板中包含什么:

#What I want to do in the template      
for i in AllLights:
print(AllLights[i].id)
print(AllLights[i].state)
print(AllLights[i].bri)
return render(request, 'file.html', 'lights': AllLights)

#What I've tried
{% for light in lights %}
{% for i in light %}
{{lights.light.id}} #light being the variable from above.
{% endfor %}
{% endfor %}

我还尝试过使用自定义模板标签:

from django import template
register = template.Library()

@register.filter
def lights(LightDict, i):
return LightDict[int(i)]
#template
{{ AllLights|lights.forloop.counter0 }}

总结一下我想做的事情。我想将 AllLights 字典传递到我的模板,然后循环遍历所有键并调用 idstatebri 每个键。

更新:

有人问我在渲染之前打印(AllLights)时会发生什么:

{'5': <dashboard.views.LightStatus object at 0x106f016a0>, '6': <dashboard.views.LightStatus object at 0x106f01320>, '7': <dashboard.views.LightStatus object at 0x106f01ac8>, '8': <dashboard.views.LightStatus object at 0x106f014e0>}

最佳答案

您(正确地)使用有序字典来维持顺序,因此假设该字典中的顺序是所需的顺序,您应该能够在模板中迭代有序字典的 :

{% for light in all_lights.values %}
{{ light.id }}
{{ light.state }}
{{ light.bri }}
{% endfor %}

关于python - 字典中的类 - Django 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47701725/

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