如何在Flask Table生成的表列中显示货币?

问题描述 投票:0回答:1

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

table.朋友

# 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')

template.html

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

routes.朋友

@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
python flask flask-sqlalchemy
1个回答
1
投票

你可以subclass the Col class

假设您的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')
© www.soinside.com 2019 - 2024. All rights reserved.