Ad
Django Template Tag: Getting Key, Value Of Dictionary
I want to access the key, value of below dictionary and output them into Django template file. However, I couldn't get the value. It raised an error. How to access each dictionary key
, and its values (option_name
, answer
, img_option
)?
Dictionary
{u'options': [{235: <OptionForm bound=False, valid=Unknown, fields=(option_name;answer;img_option)>},
{236: <OptionForm bound=False, valid=Unknown, fields=(option_name;answer;img_option)>},
{237: <OptionForm bound=False, valid=Unknown, fields=(option_name;answer;img_option)>},
{238: <OptionForm bound=False, valid=Unknown, fields=(option_name;answer;img_option)>}]
}
Django template
{% for key, option in options.items %}
<tr class="option_row rowRecord" id="{{key}}">
<td>{{option[key].option_name}}</td>
<td>{{option[key].img_option}}</td>
<td>{{option[key].answer}}</td>
<td><i class="material-icons option-delete">delete</i></td>
</tr>
{% endfor %}
ERROR Raised
TemplateSyntaxError: Could not parse the remainder: '[0].option_name' from 'option[0].option_name'
Ad
Answer
Dirty solution (because your original dict has nested list and dicts):
{% for key, values in options.items %}
{% for value in values %}
{% for k, v in value.items %}
key = {{ k }}
val = {{ v }}
{% endfor %}
{% endfor %}
{% endfor %}
Better Solution:
You should consider flattening your dictionary so that it becomes easier to loop over. You don't need nested lists and dicts. Example:
options = {
235: <Option ...>,
236: <Option ...>,
237: <Option ...>,
238: <Option ...>,
}
Now, you'll be able to loop over it in a single loop.
Ad
source: stackoverflow.com
Related Questions
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Can't turn off Javascript using Selenium
- → WebDriver click() vs JavaScript click()
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module
Ad