django format date on user supplied locale

2.8k Views Asked by At

I'm trying to set up the formatting of dates in templates based on a locale supplied by the user. As the rest of the page will remain in the original local ('en'), I only want my users' supplied data to be formatted.

for example, dates.

users in the uk should be able to use l10n on the dates on their pages, but I don't want to set the whole site to be en_GB.

is there a way to set the locale in a template within a block, eg. something like

{% locale|'en_GB' %}
    {{ my_date|localize }}
{% endlocale %}
1

There are 1 best solutions below

0
On

You don't need to do anything explicit in the template.

Inside your settings.py define the FORMAT_MODULE_PATH setting. Like:

FORMAT_MODULE_PATH = 'myproject.myapp.formats'

under the formats directory create one python package per supported language(other than your default) of your project. Inside each of these you should have a formats.py which should have any localized formatting options.

In my case the default language for my project is en, but I also support el(greek). So I have this in my settings.py:

FORMAT_MODULE_PATH = 'myproject.websiteapp.formats'

Inside the myproject/websiteapp/formats directory I have a el package with a formats.py file, like:

el/
 __init__.py
 formats.py

Inside the formats.py I have this:

DATETIME_FORMAT="l j M Y, g:i a"

which is the greek specific representation of a date.

So when I use a datetime field inside my templates:

{{ mymodel.pub_date }}

It prints the default en representation when locale is set to the default:

Published on: Feb. 22, 2013, 1:47 p.m.

and my custom greek one when the locale is set to el.

Δημοσιεύτηκε: Τετάρτη 6 Φεβ 2013, 5:39 μμ.

More info here

Edit

Hmm, I just realized that you asked for specific template blocks or values. Maybe the localize template filter or the localize template tag are more relevant to your specific case?