5

I am trying to follow this solution, in order to create a datetime filter for my date values inside a template. The advantage of using babel would be the i18n.

I have inserted the code into a file called filter.py in my application package:

from f11_app import app
import babel

def format_datetime(value, format='medium'):
    if format == 'full':
        format="EEEE, d. MMMM y 'at' HH:mm"
    elif format == 'medium':
        format="EE dd.MM.y HH:mm"
    return babel.format_datetime(value, format)

app.jinja_env.filters['datetime'] = format_datetime  

Now the error I get is:

File "/home/kave/projects/F11/Engineering/f11_app/templates/show_records.html", line 19, in block "body"

<td>{{ record.record_date|datetime }}

File "/home/kave/projects/F11/Engineering/f11_app/filters.py", line 9, in format_datetime

AttributeError: 'module' object has no attribute 'format_datetime'

In order to load the filters.py, the last line of my f11_app's __init__.py is this:

from f11_app import views, filters

What could I be missing please?

Community
  • 1
  • 1
Houman
  • 64,245
  • 87
  • 278
  • 460

1 Answers1

10

This because babel module didn't have format_datetime method. You must use babel.dates.format_datetime or flask.ext.babel.format_datetime. See: http://babel.edgewall.org/wiki/Documentation/0.9/dates.html and http://pythonhosted.org/Flask-Babel/#formatting-dates.

You also can add filter with decorator:

@app.template_filter('datetime')
def format_datetime(value, format='medium'):
    if format == 'full':
        format="EEEE, d. MMMM y 'at' HH:mm"
    elif format == 'medium':
        format="EE dd.MM.y HH:mm"
    return babel.format_datetime(value, format)
tbicr
  • 24,790
  • 12
  • 81
  • 106
  • Yes, i was using the wrong namespace `import babel` instead of 'from babel.dates import format_date' many thanks – Houman Jun 10 '13 at 10:02