【问题标题】:Django - customize result list - add element IDDjango - 自定义结果列表 - 添加元素 ID
【发布时间】:2012-11-06 03:29:35
【问题描述】:

我想覆盖默认的管理面板结果列表 (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?

【问题讨论】:

  • {{ID}} 这个属于什么?你在这里需要什么身份证?出于什么原因?
  • 它只是一个占位符。我需要这个,因为我想创建拖放功能(JS)来对项目进行排序。所以我需要每个 TR 的 id。

标签: django django-templates django-admin


【解决方案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”中的项目。

【讨论】:

  • 有效!我不知道它是否是最佳的,但它工作正常。谢谢!
  • 欢迎。不,这不是最佳的。编写自定义模板标签来执行 las >tr.. 部分将是最佳的
  • 嗨。我明白。我也在考虑将 results 传递给模板并添加 pk. 的覆盖函数
【解决方案2】:

result.form 附加到results 列表的事实来看,我猜{{ result.form.instance.id }}

只是演绎推理。如果有错请告诉我。

【讨论】:

    猜你喜欢
    • 2016-05-26
    • 2011-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-03
    • 1970-01-01
    • 2020-10-18
    • 2021-11-28
    相关资源
    最近更新 更多