I have a dictionary in my template that I want to loop through in the usual way
{% for key, value in dictionary.items %}
But in dictionary I have a key called 'items'
, so my loop return the value of dictionary['items'] and tries to unpack the result as key, value.
How can I tell Django to use the function items
instead of accessing the key?
To iterate through dictionary in a dictionary in a Python Django template, we can loop through the items with a for loop. to loop through the data dict's entries with a for loop. We get the key value pairs with data.
Loop through multiple lists If you want to send multiple lists to Django template, it is advisable to use zip function and convert it into a tuple of lists before sending them in your response. Here is an example. zip function above packs all the lists into a single list of tuples (ID, name, age).
{% %} and {{ }} are part of Django templating language. They are used to pass the variables from views to template. {% %} is basically used when you have an expression and are called tags while {{ }} is used to simply access the variable.
{% include %} Processes a partial template. Any variables in the parent template will be available in the partial template. Variables set from the partial template using the set or assign tags will be available in the parent template.
Call dictionary.iteritems
instead? I don't think there's a better way.
If you have no control over dictionary keys, the only safe way is a custom tag for iterating over dicts.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With