Reputation: 441
I am trying to pass a list of Python dictionaries to the Form on POST, and not sure how to do it. I am assembling a dictionary, then add it to a master dictionary, and pass them to the FORM for display.
Very simplified example:
Views.py
vehicles = {
'vehicle1': {'car': 'pontiac', 'engine': '400', 'model': 'GTO'},
'vehicle2': {'car': 'chevrolet', 'engine': '396', 'model': 'Chevelle'},
'vehicle3': {'car': 'ford', 'engine': '289', 'model': 'Mustang'}
}
return render(request, "vehicle_detail.html", {'vehicles': vehicles})
HTML
<p>
{% for vehicle in vehicles %}
<b>{{ vehicle.car }}</b>
<b>{{ vehicle.engine }}</b>
<b>{{ vehicle.model }}</b>
{% endfor %}
</p>
I have tried several different ways to do this, but not working. What is the proper way to handle this?
Upvotes: 1
Views: 2037
Reputation: 477210
.values()
of a dict
ionaryYou want to iterate over the values of the dictionary, so you can write:
<p>
{% for vehicle in vehicles.values %}
<b>{{ vehicle.car }}</b>
<b>{{ vehicle.engine }}</b>
<b>{{ vehicle.model }}</b>
{% endfor %}
</p>
Note however that dictionaries in Python are unordered, so the order in which the elements are rendered can swap (for example one time the Pontiac will be rendered before the Ford, and sometimes the other way around. You can not solve this in the template, since at that time, the order is already lost.
tuple
, list
, ...You can however use a a list, tuple, or other data structure that retains the order, for example:
vehicles = [
{'car': 'pontiac', 'engine': '400', 'model': 'GTO'},
{'car': 'chevrolet', 'engine': '396', 'model': 'Chevelle'},
{'car': 'ford', 'engine': '289', 'model': 'Mustang'}
]
return render(request, "vehicle_detail.html", {'vehicles': vehicles})
In that case it is simply:
<p>
{% for vehicle in vehicles %}
<b>{{ vehicle.car }}</b>
<b>{{ vehicle.engine }}</b>
<b>{{ vehicle.model }}</b>
{% endfor %}
</p>
Upvotes: 2
Reputation: 93
The way you are referencing your dictionary is correct however you are not correctly referencing the dictionary in Views.py
This would be the correct way to do it:
return render(request, "vehicle_detail.html", {'vehicles': vehicles.items()})
this should work you could also do this in your HTML like following:
{% for vehicle in vehicles.items() %}
Upvotes: 1