Answer the question
In order to leave comments, you need to log in
How to loop through the attributes of an object in a template?
The bar
object with attributes attr1 , attr2 , attr3 , attr4 is passed to the template .
You need to wrap the value of each attribute in a div:
<div class="hello">
{{ bar.attr1 }}
</div>
<div class="hello">
{{ bar.attr2 }}
</div>
<div class="hello">
{{ bar.attr3 }}
</div>
<div class="hello">
{{ bar.attr4 }}
</div>
{% for item in bar %}
{{ item }}
{% endfor %}
bar_attrs = ["attr1", "attr2", "attr3", "attr4"]
{% for attr in bar_attrs %}
{{ getattr(bar, attr) }}
{% endfor %}
Answer the question
In order to leave comments, you need to log in
views.py:
bar_attrs = ["attr1", "attr2", "attr3", "attr4"]
context['bar_vals'] = [getattr(bar, i) for i in bar_attrs]
{% for item in bar_vals %}
<div class="hello">
{{ item }}
</div>
{% endfor %}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question