1

Seems trivial, but I'm iterating a dictionary, accessing another dictionary from the id key of that dict. Example:

{% for choice in choices %}
  {{ percentages[choice.id] }}
{% endfor %}

As in:

for choice in choices:
  percentages[choice.id]

Though I get a Django error:

Could not parse the remainder: '[choice.id]' from 'percentages[choice.id]'

Which I thought may work. I tried researching and changing [choice.id] into |get:choice.id as a potential resolution, but that also gave me another unhelpful error.

Jack Hales
  • 1,574
  • 23
  • 51
  • I think this solution will solve your problem [https://stackoverflow.com/questions/1275735/how-to-access-dictionary-element-in-django-template](https://stackoverflow.com/questions/1275735/how-to-access-dictionary-element-in-django-template) – HERAwais Apr 11 '19 at 02:37
  • Possible duplicate of [how to access dictionary element in django template?](https://stackoverflow.com/questions/1275735/how-to-access-dictionary-element-in-django-template) – HERAwais Apr 11 '19 at 02:40
  • 1
    @HERAwais I think this holds SO integrity. The core question is indeed accessing dictionaries, though my confusion came from the iterating aspect. Since this question comes from the Django tutorial, I think future people will come across it with the same questions. If not, that's fair enough. – Jack Hales Apr 11 '19 at 02:43

1 Answers1

3

You cannot access dictionary indices from django template. You have to register a custom template tag like this.

@register.filter
def from_dict(d, k):
    return d[k]

And use it like this.

{% for choice in choices %}
  {{ percentages|from_dict:choice.id }}
{% endfor %}
Nafees Anwar
  • 6,324
  • 2
  • 23
  • 42
  • That's neat. Where does this code reside? Above my views? – Jack Hales Apr 11 '19 at 02:39
  • 1
    You have to create a package named `templatetags` inside your app and put a file in it (like `extras.py`). Then load them in templates like this `{% load extras %}`. Please see more on this [here](https://docs.djangoproject.com/en/2.2/howto/custom-template-tags/) – Nafees Anwar Apr 11 '19 at 02:43