pythondjangodjango-templatesdjango-tagging

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'


Solution

  • 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.