在django模板中显示第一个字母

时间:2013-12-09 09:56:16

标签: python django templates

我试图在django模板中显示QuerySet的每个成员的第一个字母:

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>

但是当我尝试渲染页面时出现错误:

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]'

我应该在将QuerySet传递给模板之前对其进行操作吗?

1 个答案:

答案 0 :(得分:4)

这将有效:{{ dept.name.0 }}

文档说:

  
    

从技术上讲,当模板系统遇到一个点时,它会按以下顺序尝试以下查找:     

字典查找
属性查找
方法调用         
列表索引查找

  

Reference link

相关问题