1๐
โ
If you write:
{{weather_object.variable }}
it aims to obtain the attribute named variable
from the weather_object
, and if that fails, it will try to use weather_object['variable']
. The fact that there is a variable named variable
does not matter. That would also be very unstable: imagine that you assign a variable named humidity = 'temp'
. It would easily break the application since now all item.humidity
s all of a sudden should use item.temp
instead. That would be bad code design.
However a template should not implement business logic: it should only implement rendering logic. It is the view that needs to pass data in an accessible way to the view.
You for example can construct a list of lists for your weather_objects
with:
variable_list = ['temp', 'humidity']
weather_data = [
[getattr(datum, v) for v in variable_list]
for datum in wheather_objects
]
context = {'weather_data': weather_data }
return render(
request,
'webapp/detail.html',
context=context
)
and then render this as:
<table>
{% for weather_object in weather_data %}
<tr>
{% for item in weather_object %}
<td>{{ item }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
Source:stackexchange.com