【发布时间】:2022-01-10 02:20:01
【问题描述】:
我有一个充满天气对象的查询集,我需要循环访问一个自定义数组,以在 Django 应用程序的 HTML 模板中提取每个天气对象中的特定天气指标。
detail.html
<table>
<tr>
{% for weather_object in weather_objects %}
{% for variable in variable_list %} ## variable_list = ['temp', 'humidity']
<td>{{weather_object.variable}}</td>
{% endfor %}
{% endfor %}
</tr>
</table>
Views.py
context = {'weather_objects': weather_objects,
'variable_list': variable_list}
return render(
request,
'webapp/detail.html',
context=context
)
可能有更好的方法来做到这一点,但老实说,我真的很难过。为什么我不能遍历变量列表并从weather_object 中提取数据?特别是“weather_object.variable”,它的作用并不存在。
我可以手动做,我可以专门写
<td>{{weather_objects.temp}}</td>
或
<td>{{weather_objects.humidity}}</td>
但我无法在 for 循环中自动执行它。为什么??我已经验证变量列表中的变量是正确的并且应该可以工作。难道是因为变量只是一个字符串替换?
【问题讨论】:
-
因为
{{ weather_object.variable }}将寻找weather_object.variable(所以一个属性命名variable)和weather_object['variable'],而不是weather_object.temp或weather_object['temp']如果'temp'分配给variable。
标签: python html django for-loop