使用django-tables2时如何格式化浮点数的显示?

How to format the display of floats when using django-tables2?

我正在使用 django-tables2 来显示一些数据。我有一列浮点数,希望它们只显示到小数点后两位(因此,10.238324 将显示为 10.24)。有没有简单的方法可以做到这一点?在 Django 模板中,我使用 {{number||floatformat:2}} 执行此操作。

可能相关的文档:
http://django-tables2.readthedocs.io/en/latest/pages/column-attributes.html.

1。在视图中舍入您的数据

实际上,这并不直接控制数字的 显示 ,并且会省略不需要小数的值(24.1 而不是 24.10).这是一个快速的解决方案,因为您必须修改自己的观点。然而,这不是一个好的风格。

2。替换 django_tables2 呈现的模板

文档说你可以 use your own table template

默认模板 (source code) 包含您可以覆盖的块。我认为这是要走的路。您自己的 float_table.html 可能类似于此示例:

{% extends "table.html" %} {# hope that finds the original template #}
{% block table.tbody.row %}
    <tr {{ row.attrs.as_html }}>
        {% for column, cell in row.items %}
            <td {{ column.attrs.td.as_html }}>{% if column.localize == None %}{{ cell|floatformat:2 }}{% else %}{% if column.localize %}{{ cell|localize }}{% else %}{{ cell|unlocalize }}{% endif %}{% endif %}</td>
        {% endfor %}
    </tr>
{% endblock table.tbody.row %}

这会将 floatformat 过滤器应用于每个未定义 localize 属性的列。如果您不想在格式上更加个性化,那么呈现每个单元格似乎是获得您想要的内容的最少干扰方式。

如果你想要更细粒度,那就更难了。我认为高级模块的微调很少是美好的:)

3。通过 javascript

添加 <td><tr> 属性和格式

只是为了完整性,也不是我推荐的方式:文档告诉您如何 add custom attributes to rows or columns。你可以用它作为一个钩子来添加一个 class 比如 float2。通过 javascript(也许也可以通过 CSS 以某种方式?)然后您可以对呈现的内容进行舍入。


所以我认为选项 2 确实是最干净的方法。如果您不感兴趣,您甚至可以简化模板片段而不检查本地化。

我认为 django_tables2 有一个用于将模板过滤器链接到单元格内容的挂钩将是一个不错的功能。也许您向他们发送了功能请求:)

如果您只有一列带有浮点数,请将您的值格式化为 render_<column_name>() method:

class NumberTable(tables.Table):
    number = tables.Column()

    def render_number(self, value):
        return '{:0.2f}'.format(value)

如果您有多个带浮点数的列,您可以定义一个 custom column 并重复使用它:

class NumberColumn(tables.Column):
    def render(self, value):
        return '{:0.2f}'.format(value)


class NumberTable(tables.Table):
    temperature = NumberColumn()
    pressure = NumberColumn()
    flow = NumberColumn()

此自定义列还可以实现一个自定义构造函数,如果您想改变小数位数的话。

您也可以使用 :

class DecimalColumn(tables.Column):
    '''Column to normalize decimals'''

    def render(self, value):
        return value.normalize()

用法:

class MyTable(tables.Table):
    amount = DecimalColumn()