Flask-Admin formatters examples

To customize how the model’s columns are displayed in the list of objects in Flask-Admin, it requires column formatters. Here are some examples.

Column type formatters

import json
from bson import json_util
from datetime import date
from flask_admin.model import typefmt
from markupsafe import Markup

def pre_format(view, value):
    return Markup('<div class="pre">{}</div>'.format(html.escape(value)))

def json_format(view, value):  
    # useful for mongoengine dict and list fields
    return pre_format(view, json.dumps(value, indent=2, default=json_util.default))

def date_format(view, value):
    return value.strftime('%d.%m.%Y %H:%M:%S')

    date: date_format,
    dict: json_format

class MyModelView(ModelView):
    column_type_formatters = MY_DEFAULT_FORMATTERS

Override admin/base.html and define your styles, for example:

    .pre {
        white-space: pre;
        overflow-y: auto;
    .model-list .pre {
        max-width: 300px;

Column formatters

def user_link_formatter(view, context, model, name):
    field = getattr(model, name)
    url = url_for('user.details_view', id=field.id)
    return Markup('<a href="{}">{}</a>'.format(url, field))

class SomeModelView(MyModelView):
	"""An admin view for a model with user reference."""
    column_formatters = {
        'user': user_link_formatter

base64 image

def base64_image_formatter(view, context, model, name):
    field = getattr(model, name, '')
    if field:
        field = Markup('<img src="data:image/jpg;base64,{}" width="100"/>'.format(field))
    return field


def timestamp_formatter(view, context, model, name):
    field = getattr(model, name, None)
    return (field and datetime.utcfromtimestamp(field)) or ''


def json_formatter(view, context, model, name):
    return json_format(view, getattr(model, name, None))


def html_formatter(view, context, model, name):
    return pre_format(view, getattr(model, name, ''))
comments powered by Disqus