Sean McCarthy
Sean McCarthy

Reputation: 5578

Flask Admin right-align values in table view

Using the Flask Admin package to view database tables, how to right-align the values in the cells? See code below.

flask admin table of sales by year and employee

class VwSalesByPersonYearView(MyModelView):
    """VwSalesByPersonYear model view"""

    can_create = False
    can_edit = False
    can_delete = False
    column_display_pk = False
    can_set_page_size = True
    page_size = 50

    column_list = (
        "service_year",
        "name_",
        "sales_total",
    )
    column_labels = {
        "service_year": "Year",
        "name_": "Employee",
        "sales_total": "Total Sales",
    }
    column_descriptions = {
        "service_year": "Year of the sales",
        "sales_total": "Total sales (i.e. labour + parts)",
    }
    column_sortable_list = (
        "service_year",
        "name_",
        "sales_total",
    )
    column_default_sort = [
        ("service_year", True),
        ("sales_total", True),
        ("name_", True),
    ]
    column_filters = (
        "service_year",
        "name_",
        "sales_total",
    )
    column_searchable_list = (
        "service_year",
        "name_",
    )
    column_formatters = {
        "service_year": lambda v, c, m, n: f"{m.service_year:.0f}",
        "sales_total": lambda v, c, m, n: f"{m.sales_total or 0:,.0f}",
    }

Upvotes: 0

Views: 31

Answers (1)

Sean McCarthy
Sean McCarthy

Reputation: 5578

I found a solution: use Markup with style="text-align: right;" in the column_formatters:

from markupsafe import Markup

...

    column_formatters = {
        "service_year": lambda v, c, m, n: f"{m.service_year:.0f}",
        "sales_total": lambda v, c, m, n: Markup(f'<div style="text-align: right;">{m.sales_total or 0:,.0f}</div>'),
    }

Here's a really easy way to format numbers with options in Flask Admin:


def get_number_formatter(
    decimals: int = 0, right_align: bool = True, dollar_sign: bool = False
) -> callable:
    """Format a number with commas and a certain number of decimals"""

    def formatter(view, context, model, name: str) -> Markup:
        """Format a number with commas and a certain number of decimals"""

        attr = getattr(model, name, None)
        if isinstance(attr, (Number, Decimal, float, int)):
            new_str = f"{attr:,.{decimals}f}"
        elif attr is None:
            new_str = ""
        else:
            new_str = attr

        if dollar_sign:
            new_str = f"${new_str}"

        if right_align:
            return Markup(f'<div style="text-align: right;">{new_str}</div>')

        return new_str

    return formatter

...

    column_formatters = {
        "service_year": lambda v, c, m, n: f"{m.service_year:.0f}",
        "sales_total": get_number_formatter(
            decimals=0, right_align=True, dollar_sign=True
        ),

Upvotes: 0

Related Questions