djangon00b
djangon00b

Reputation: 351

Accessing individual objects in a Django template file

I am editing a template to display an attribute of the first member in a list. I am trying to access it like so:

{{ food_list.index(0).id }}

I get an error that says Could not parse the remainder: '(0).id'. What is the correct way to access an individual member in a list?

Upvotes: 0

Views: 55

Answers (2)

Ismail Badawi
Ismail Badawi

Reputation: 37177

{{ food_list.0.id }}

Alternatively,

{% with f=food_list|first %}
  {{ f.id }}
{% endwith %}

Upvotes: 3

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798676

You can't call methods in a template. Either write a template tag for this, or do it in your view. If what you wanted to do was just index the list, then you don't use the index() method for that; just use normal dot notation instead.

Upvotes: 1

Related Questions