Patrick Kaim
Patrick Kaim

Reputation: 66

How do I display currency in a Flask Table generated table column?

flask-table does have several specific column types. For example date: DateCol. But there is no column type for currency. So for now data is displayed using the standard Col type. Now you just get a Decimal. It works but I'd would prefer a currency format.

Table.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')

template.html

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

routes.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)

result:

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

what I would like to accomplish:

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

Upvotes: 0

Views: 1067

Answers (1)

atwalsh
atwalsh

Reputation: 3722

You could subclass the Col class.

Assuming your amount data is stored as a string (such as 1,523.78), you could do something like this:

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

Then change your table to use the new CurrencyCol:

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

Upvotes: 2

Related Questions