How to access a dictionary element in a Django template?

0 votes

I would like to print out the number of votes that each choice got. I have this code in a template:

{% for choice in choices %}
    {{choice.choice}} - {{votes[choice.id]}} <br />
{% endfor %}

votes is just a dictionary while choices is a model object.

It raises an exception with this message:

"Could not parse the remainder"
Jul 3 in Python by kartik
• 19,630 points
71 views

1 answer to this question.

0 votes

Hello @kartik,

Use Dictionary Items:

{% for key, value in my_dictionay.items %}
  <li>{{ key }} : {{ value }}</li>
{% endfor %}

Hope it works!!

Thank you!

answered Jul 3 by Niroj
• 41,480 points

Related Questions In Python

0 votes
1 answer

How to check if an element is present in a Django queryset?

Hello @kartik, You can use the following code: if ...READ MORE

answered May 27 in Python by Niroj
• 41,480 points
194 views
0 votes
1 answer

How to do math in a Django template?

Hello @kartik, You can use the add filter: {{ object.article.rating_score|add:"-100" }} Thank ...READ MORE

answered Jun 23 in Python by Niroj
• 41,480 points
67 views
0 votes
1 answer

How to call function that takes an argument in a Django template?

Hello @kartik, You cannot call a function that ...READ MORE

answered Jun 23 in Python by Niroj
• 41,480 points
45 views
0 votes
1 answer

How to output text from database with line breaks in a django template?

Hello @kartik, Use linebreaks or linebreaksbr filter: {{ text|linebreaks }} Or surround the text ...READ MORE

answered Jun 24 in Python by Niroj
• 41,480 points
76 views
0 votes
1 answer

How to temporarily disable a foreign key constraint in MySQL?

Hello @kartik, To turn off foreign key constraint ...READ MORE

answered Jun 23 in Python by Niroj
• 41,480 points
58 views
0 votes
1 answer

How do I use Django templates without the rest of Django?

Hello @kartik, Let's say you have this important ...READ MORE

answered Jun 23 in Python by Niroj
• 41,480 points
40 views
0 votes
1 answer

How to access the user profile in a Django template?

Hello @kartik, In your profile model provide related_name user ...READ MORE

answered 5 days ago in Python by Niroj
• 41,480 points
14 views
0 votes
1 answer

How to look up a dictionary value with a variable in Django template?

Hii @kartik, Write a custom template filter: from django.template.defaulttags ...READ MORE

answered 13 hours ago in Python by Niroj
• 41,480 points
11 views