【问题标题】:Customizing Django Admin Result List自定义 Django 管理结果列表
【发布时间】:2011-03-17 11:52:52
【问题描述】:

如何更改 Django 管理结果列表的输出结果?我一直在研究 change_result_list.html 模板文件,但我只能找到:

{% for item in result %}{{ item }}{% endfor %}

这将输出类似:

<tr>
    <td>
        <input type="checkbox" class="action-select" value="2" name="_selected_action" />
    </td>
    <th>
        <a href="1/">Lorem Ipsum</a>
    </th>
</tr>

显然,th 元素破坏了我的设计。有没有办法把它改成td

【问题讨论】:

    标签: django django-admin django-templates


    【解决方案1】:

    没有“简单”的方法可以做到这一点,所以我必须首先问你为什么需要这样做。我不明白为什么 &lt;th&gt; 元素应该“明显”破坏您的设计。 &lt;th&gt; 元素等价于&lt;td&gt;,除了默认情况下有额外的样式(通常是font-weight: bold; text-align: center;)。您应该能够在您的 CSS 中考虑到这一点。

    也就是说,这里有一些方法可以查看。 th/td 选择在django.contrib.admin.templatetags.admin_list.py 的第 169 行 (Django 1.2.1) 上确定。以下是它出现的上下文的摘要:

    def items_for_result(cl, result, form):
        first = True
        for field_name in cl.list_display:
            # ...
            if (first and not cl.list_display_links) or field_name in cl.list_display_links:
                table_tag = {True:'th', False:'td'}[first]
                first = False
                # ...
                yield mark_safe(u'<%s%s><a href="%s"%s>%s</a></%s>' % (table_tag, row_class, url, ...)
            else:
                # ...
                yield mark_safe(u'<td%s>%s</td>' % (row_class, result_repr))
    

    如您所见,没有明显的方法可以改变决定 table_tag 值的行为,所以您有一些选择:

    • 定义一个“items_for_result”模板标签,它调用上面的模板标签,并将生成的值中的任何&lt;th&gt;s 替换为&lt;td&gt;s。然后你可以覆盖 "change_list.html" 并在 "admin_list" 加载后 {% load %} 标记。
    • 编辑 Django 代码。不过你以后会后悔的。
    • 如果您认为表格中的所有列都不是项目编辑页面的链接(我无法想象您为什么会这样做),您可以在 admin.py 中使用这个丑陋的 hack:

      admin.site.register(YourModel, YourModelAdmin)
      admin.site._registry[YourModel].list_display_links = ['not_a_field_name',]`
      

      由于管理模型只验证一次,这发生在调用 register() 时,您可以在之后获取已注册的 ModelAdmin 并给它一个无效的 list_display_links 属性。

    【讨论】:

    • 确实,编辑 CSS 更容易。但是,从可用性的角度(以及我的理想主义)来看,th 应该只用于标题单元格。为什么他们使用 th 而不是 td,这有点荒谬。
    猜你喜欢
    • 2011-02-05
    • 2020-04-01
    • 2012-03-23
    • 1970-01-01
    • 1970-01-01
    • 2012-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多