ChatGPT解决这个技术问题 Extra ChatGPT

Django Templating: how to access properties of the first item in a list

Pretty simple. I have a Python list that I am passing to a Django template.

I can specifically access the first item in this list using

{{ thelist|first }}

However, I also want to access a property of that item... ideally you'd think it would look like this:

{{ thelist|first.propertyName }}

But alas, it does not.

Is there any template solution to this, or am I just going to find myself passing an extra template variable...


D
Daniel Roseman

You can access any item in a list via its index number. In a template this works the same as any other property lookup:

{{ thelist.0.propertyName }}

Hmm. this doesnt work with an inline_admin_formset however. I guess the iterator doesnt work how I expect it to.
Hi Daniel, Could you check my question related to template/view stackoverflow.com/questions/34791375/… ?
This is much better than a for loop to go through each of the error messages. Thanks!
And thelist.-1.propertyName for the last item?
No, that wouldn't work unfortunately, Django can't parse that. You would need to use the with tag along with |last, as Mark suggests in the other answer.
M
Mark Lavin

You can combine the with template tag with the first template filter to access the property.

{% with thelist|first as first_object %}
    {{ first_object.propertyname }}
{% endwith %}

For a dictionary, first returns a tuple for the key/value pair, it's a bit ugly but I added another with statement to get just the values. {% with thelist|first as first_object %}{% with first_object.1 as object %}{{ object }}{% endwith %}{% endwith %}
佚名

If you're trying to access a manytomany field, remember to add all, so it will look like object.m2m_field.all.0.item_property


Could give you +10 mentioning "all", you saved my day ;)
R
RealScatman

a potentially clearer answer/syntax for accessing a ManyToManyField property in an object list provided to the django template would look like this:

{{ object_list.0.m2m_fieldname.all.0.item_property }}