Django template error: could not parse the remainder

Django template error: could not parse the remainder

我正在尝试从 Django(1.6.11) 模板中的字典呈现一个值。 unit_list 是单位(型号)列表。 unit.unit_id是unit的主键。 tags_dict 是标签的字典,其中 unit_ids 作为键,标签作为值。

{% for unit in unit_list %}
<tr>
    <td>{{ unit.unit_id }}</td>
    <td>{{ unit.version }}</td>
    <td>{{ unit.release_dt|date:'Y-m-d' }} {{ unit.release_dt|time:'H:i:s' }}</td>
    <td>{{ unit.update_dt|date:'Y-m-d' }} {{ unit.update_dt|time:'H:i:s' }}</td>
    <td>
        {{ tags_dict[unicode(unit)] }}
    </td>
    <td>{{ unit.last_modified|date:'Y-m-d' }} {{ unit.last_modified|time:'H:i:s' }}</td>
</tr>
{% endfor %}

但是我得到了这个错误:

Could not parse the remainder: '(unicode(unit))' from 'tags_dict.get(unicode(unit))'

这是因为您不能将这样的函数调用放入 Django 模板中。看起来您应该在视图中执行此操作并将其作为变量传递给模板。您还可以在单​​元 class 上添加一个方法,如下所示:

def get_tags(self):
    tags_dict = {} # TODO: retrieve tags dict.
    return tags_dict[unicode(self)]

然后,您可以在模板中做这样的事情:{{ unit.get_tags }}

像这样删除空格:

<td>{{unit.last_modified|date:'Y-m-d'}}{{unit.last_modified|time:'H:i:s'}}</td>