首页 > 解决方案 > 如何在 Flask Table 生成的表格列中显示货币?

问题描述

flask-table 确实有几种特定的列类型。例如日期:DateCol。但是没有货币的列类型。所以现在数据使用标准的 Col 类型显示。现在你只得到一个小数。它有效,但我更喜欢货币格式。

表.py

# import things
from flask_table import Table, Col, DateCol

# Declare my table
class MyTable(Table):
    classes = ['table', 'table-hover']
    id = Col('id')
    amount = Col('amount')
    date = DateCol('date')

模板.html

<div>{{ amounts_table }}</div>

路线.py

@route('/my_table')
def my_table():
    table_content = Amounts.query.all()
    amounts_table = AmountsTable(table_content)
    return render_template('template.html', amounts_table=amounts_table)

结果:

id     amount       date
1      1,523.78     30-03-2019

我想完成什么:

id     amount       date
1      € 1.523,78   30-03-2019

标签: pythonflaskflask-sqlalchemy

解决方案


您可以将类子Col化。

假设您的amount数据存储为字符串(例如1,523.78),您可以执行以下操作:

# Python 3.7

import locale

class CurrencyCol(Col):
    def td_format(self, content):
        amount = float(content.replace(',', ''))
        locale.setlocale(locale.LC_NUMERIC, 'nl_NL')
        val = locale.format_string('%.2f', float(amount), 1, 1).replace(' ', '.')
        return f'€ {val}'

然后更改您的表以使用新的CurrencyCol

class MyTable(Table):
    classes = ['table', 'table-hover']
    id = Col('id')
    amount = CurrencyCol('amount')
    date = DateCol('date')

推荐阅读