Question

I want to change the default way dates are presented to me in the flask admin, to give it a specific timezone and display it in a more human-readable format.

There are a number of ways of going about this (filters, __html__, __str__, Babel, etc), but while these could work, my question is whether there is a more general approach for a more general problem. The specific problem of formatting dates is just an example.

In my scenario, I don't have control over the date object -- I can't subclass it or monkeypatch a __str__ or __html__ method. I want it to happen automatically for all dates in the templates, and I don't want to have to write custom admin templates, and I don't want to have to use explicit filters in my templates for this scenario.

My ideal solution would be to somehow specify a default filter to Jinja, so that all data was passed through that filter before being presented. I can write the filter myself, but I can't see how to get Jinja to use it.

One thought I had was to use autoescaping somehow (see this question), but I can't see any way to override Jinja's autoescaping functionality without nasty monkeypatching.

Any ideas?

No correct solution

OTHER TIPS

You don't have to monkeypatch anything.

You just create a custom base class for your Model views with custom formatters. An example for date class:

from datetime import date
from flask_admin.model import typefmt


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

MY_DEFAULT_FORMATTERS = dict(typefmt.BASE_FORMATTERS)
MY_DEFAULT_FORMATTERS.update({
    date: date_format,
})

class MyModelView(BaseModelView):
    column_type_formatters = MY_DEFAULT_FORMATTERS

If you want that in Flask-Admin related code, you can rely on column_type_formatters.

https://flask-admin.readthedocs.org/en/latest/api/mod_model/#flask.ext.admin.model.BaseModelView.column_type_formatters

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top