1

"dishList" is a list of "dish" object and "dish" object includes an "id" field. For example:

dishList = [dish1, dish2, dish3, ...]
dish1.id = 1

"dishCount" is a dictionary type in python, which include a number for each dish. For example:

dishCount = { dish1.id: 0, dish2.id: 0, ...}

My problem is that in this for loop:

{% for d in dishList %}

How can I assess the number of dish "d"? I want to use {{ dishCount.(d.id) }} but it is not working.

Could not parse the remainder: '(d.id)' from 'dishCount.(d.id)'

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • The django templating language is designed to focus on the display, not on the logic. So it's not possible to fetch elements of a dictionary by a variable key. You could write a template filter that does that, but it's probably better if your view sends a different context to your template, where your list of dishes already has the counts. – dirkgroten Sep 19 '19 at 17:56

2 Answers2

1

How can I assess the number of dish "d"?

Django's template languages is deliberately restricted not to allow subscripting and function calls (with parameters). You strictly speaking can use a template filter for that, or use a template engine like jinja.

The reason why it is however restricted is more interesting: it aims to prevent users from writing business logic in the templates. It is usually better to write that in the view.

You thus can add an attribute to your dishes, like:

dishList = [dish1, dish2, dish3]
dishCount = { dish1.id: 0, dish2.id: 0}
for dish in dishList:
    dish.count = dishCount[dish.id]

Then you can render this with:

{% for d in dishList %}
    {{ d.count }}
{% endfor %}
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
0

You can make custome template tag or you can use for loop in dict.items() in dict and get the item key and value

Django template how to look up a dictionary value with a variable

You can find out more here

Sanjay Kumar
  • 129
  • 7