-1

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'

  • As the error says, this is invalid syntax in Django templates. But **why would you do this**? You *already have*the value, there is no need to try and get it via the key. – Daniel Roseman Mar 20 '19 at 08:14
  • @DanielRoseman Each `` has key as its id. So, I need to output the key of the dictionary into it. If my approach is wrong, could you recommend me a better one? The requirement is that I need to output `key` into the `id` attribute, and get `option_name`, `answer`, `img_option` – Sokunthaneth Chhoy Mar 20 '19 at 08:18
  • What happens if you try with `{{option.option_name}}` – ruddra Mar 20 '19 at 08:20
  • @ruddra it is empty, doesn't show anything. – Sokunthaneth Chhoy Mar 20 '19 at 08:24
  • @Sokunthaneth You have more dicts inside the list. You'll have to create another loop to get those keys. – xyres Mar 20 '19 at 08:33
  • @xyres can you show me? – Sokunthaneth Chhoy Mar 20 '19 at 08:35
  • `options` is a list. Can’t you make it a dict? It’s not entirely clear what is `options` is it the entire dict with the one key “options” or is it the dict[“options”] element of the dict you show? – dirkgroten Mar 20 '19 at 08:53

1 Answers1

1

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.

xyres
  • 20,487
  • 3
  • 56
  • 85