Django’s template language does not support Python-style indexing like votes[choice.id]. That is why you are seeing the error saying it cannot parse the expression. The template system is intentionally limited, so direct dictionary lookups with brackets are not allowed.
1. Recommended: do the lookup in the view
A simple approach is to attach the vote count to each choice in the view before rendering the template. This keeps the template clean and keeps the logic in Python, which is usually easier to maintain.
View:
def poll_view(request):
choices = Choice.objects.all()
votes = get_votes_dict_somehow() # example: {1: 10, 2: 7, 3: 4}
for c in choices:
c.vote_count = votes.get(c.id, 0)
return render(request, "poll.html", {"choices": choices})
Template:
{% for choice in choices %}
{{ choice.choice }} - {{ choice.vote_count }}<br>
{% endfor %}
2. Use a custom template filter
If you really want to access the dictionary directly in the template, you can write a small filter that returns the value for a given key.
yourapp/templatetags/dict_extras.py
from django import template
register = template.Library()
@register.filter
def dict_get(d, key):
return d.get(key, "")
Template:
{% load dict_extras %}
{% for choice in choices %}
{{ choice.choice }} - {{ votes|dict_get:choice.id }}<br>
{% endfor %}
This gives you a simple and readable way to access dictionary values without using bracket notation. Both methods work, so choose whichever one fits your workflow better.