Django - 自定义结果列表 - 添加元素ID

时间:2012-11-17 17:32:24

标签: django django-templates django-admin

我想覆盖默认的管理面板结果列表(change_list_results.html),为<tr>

中的每一行添加ID

默认为:

<tbody>
        {% for result in results %}
            {% if result.form.non_field_errors %}
                <tr><td colspan="{{ result|length }}">{{ result.form.non_field_errors }}</td></tr>
            {% endif %}
            <tr class="{% cycle 'row1' 'row2' %}">{% for item in result %}{{ item }}{% endfor %}</tr>
        {% endfor %}
 </tbody>

我想:

<tbody>
        {% for result in results %}
            {% if result.form.non_field_errors %}
                <tr><td colspan="{{ result|length }}">{{ result.form.non_field_errors }}</td></tr>
            {% endif %}
            <tr class="{% cycle 'row1' 'row2' %}" id="{{ ID }}">{% for item in result %}{{ item }}{% endfor %}</tr>
        {% endfor %}
</tbody>

我应该在{{ ID }}中添加什么来获取元素ID?

2 个答案:

答案 0 :(得分:1)

不幸的是,'items'上下文变量不包含实例数据,它只是一个包含每列html的列表。要实现您的需求,您必须根据forloop计数器在'cl.result_list'上下文变量中搜索等效项:

<tr class="{% cycle 'row1' 'row2' %}" id="{% with i=forloop.counter0|stringformat:"s"|add:":" %}{% with items=cl.result_list|slice:i %}{{ items.0.pk }}{% endwith  %}{% endwith %}">{% for item in result %}{{ item }}{% endfor %}</tr>

或者,如果您不喜欢所有这些'with'标签,您可以创建一个自定义模板,直接从计数器索引中获取“cl.result_list”中的项目。

答案 1 :(得分:0)

我猜{{ result.form.instance.id }}result.form列表中附有results这一事实而判断。

只是演绎推理。如果这是错的,请告诉我。