0

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?

Community
  • 1
  • 1
bryhoyt
  • 273
  • 3
  • 10

2 Answers2

2

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
plaes
  • 31,788
  • 11
  • 91
  • 89
1

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

iurisilvio
  • 4,868
  • 1
  • 30
  • 36
  • Useful answer, thanks. Not selecting as the right answer mainly because I'm more interested in how to achieve this in general using Jinja, and my question's specifically about Jinja. – bryhoyt Mar 04 '14 at 20:12
  • No problem... I don't know if it is possible the way you want. Probably you have to use some filter. – iurisilvio Mar 05 '14 at 02:45