views:

28

answers:

2

Using {{today|time:"TIME_FORMAT"}} correctly localises times when I switch languages in my Django 1.2.3 project. E.g. for English I see "12:19 a.m." and when I switch to German it changes to "12:19:25".

As far as I can tell from looking at the docs and code (defaultfilters.py and formats.py) just using {{today:time}} should do the same thing and default to TIME_FORMAT but this isn't working and it always uses the default English format.

Is there a way to avoid having to edit all my templates and change them to {{today|time:"TIME_FORMAT"}}?

The same thing happens with the date filter and DATE_FORMAT.

+2  A: 

The docs say (emphasis mine):

When used without a format string:

 {{ value|time }}

...the formatting string defined in the TIME_FORMAT setting will be used, without applying any localization.

You have two options:

  1. Edit all your templates to make the change, or

  2. Create a new filter of your own that does it the way you want.

Ned Batchelder
Hmm, I guess I didn't see that bit of the docs. Still (assuming you're looking at http://docs.djangoproject.com/en/1.2/ref/templates/builtins/#time) it also says:"Note that the predefined format is locale- dependant." and at the very bottom "Changed in Django 1.2: Predefined formats can now be influenced by the current locale."So, it sounds like they should be able to be "influenced"...
Tom
A: 

Thanks @Ned Batchelder, as per option 2., I've added the following to my custom template tags file:

from django.template.defaultfilters import date as defaultfilters_date, time as defaultfilters_time

# FORCE {{...|date}} to be equivalent to {{...|date:"DATE_FORMAT"}} so it localizes properly, ditto for time and TIME_FORMAT

@register.filter(name="date")
def date_localized(val, arg=None):
    return defaultfilters_date(val, arg or "DATE_FORMAT")

@register.filter(name="time")
def time_localized(val, arg=None):
    return defaultfilters_time(val, arg or "TIME_FORMAT")
Tom