[英]How to print value of a "changing field" in Django template
我正在尝试在模板中显示字段列表(及其值)。 问题是字段名正在改变,我无法控制它们。 e,g 字段可以是:
field_name1
field_object1
field_input1
这里唯一不变的是前缀“field_”
这对在模板中获取该字段的值提出了挑战。 我遵循了这里的建议: Django:无法引用包含点并且能够打印字段名称的模板中的字段名称。 但我仍然不知道如何打印这些字段的值。
模型.py
rowObj = {
'id': id,
'inputList': {'Input_' + k: v for k, v in objList}
}
# Example of the outputs (The outputs can be one of the following):
# rowObj = {
# 'id': 1,
# 'inputList': {'Input_Image' : 'http://test',
# 'Input_Image2' : 'http://test2' }
# }
#another time the output can be:
# rowObj = {
# 'id': 1,
# 'inputList': {'Input_Text' : 'Random text',
# 'Input_Text2' : 'Random text 2' }
# }
我的模板是:
{% for row in row_list %}
<tr>
<td>{{ row.id }}</td>
{% for obj in row.inputList %}
<td>{{ obj }}</td>
{% endfor %}
</tr>
{% endfor %}
上面的代码只输出字段名称,即“Input_Image”和“Input_image2”我不知道如何打印这些字段的值。 你能帮忙吗。 谢谢你。
reddit 上有人回答了这个问题。 解决方案是在模板中使用以下内容:
{% for k,v in row.inputList.items %} {{ k }} : {{ v }} {% endfor %}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.