user3082242
user3082242

Reputation: 3

Show a first letter in django template

I am trying to show a first letter of each member of a QuerySet in a django template:

views.py:

deparmtents = Department.objects.all()
context = {'department_list': departments}
return render(request, 'review/index.html', context)



index.html:

<table>
    {% for dept in department_list %}
    <tr>
        <td>{{ dept.name[0] }}</td>
        <td>{{ dept }}</td>
    </tr>
    {% endfor %}
</table>

However when I try to render the page there is an error:

Request Method: GET
Request URL:    http://localhost:8000/review/
Django Version: 1.6
Exception Type: TemplateSyntaxError
Exception Value:    Could not parse the remainder: '[0]' from 'dept.name[0]'

Should I manipulate the QuerySet before passing it to the template?

Upvotes: 0

Views: 325

Answers (1)

Alex Parakhnevich
Alex Parakhnevich

Reputation: 5172

This will work: {{ dept.name.0 }}

Docs say:

Technically, when the template system encounters a dot, it tries the following lookups, in this order:

Dictionary lookup
Attribute lookup
Method call
List-index lookup

Reference link

Upvotes: 4

Related Questions