Advice on using FORMAT_MODULE_PATH

2019-08-30 15:23发布

问题:

From what I have read FORMAT_MODULE_PATH allows to use custom formats.

How can I access the first value from DATETIME_INPUT_FORMATS in my application?

The DATETIME_INPUT_FORMATS variable for german should be '%d.%m.%Y', whereas for english should be '%Y-%m-%d'. I want to use the values from the formats.py files depending on the language.

I followed the Django documentation for how to use the FORMAT_MODULE_PATH variable, but I don't get the expected results.

settings.py:
    USE_L10N = True
    USE_I18N = True
    FORMAT_MODULE_PATH = 'myproject.formats'


myproject/
    formats/
        __init__.py
        en/
            __init__.py
            formats.py
        de/
            __init__.py
            formats.py

I change the browser's language from English to German, and back and nothing happens with the date format. It is always '%Y-%m-%d'. The displayed date format is the value of settings.DATE_INPUT_FORMATS[0].

Django version is 1.2.5 and Python version is 2.5.4.

回答1:

In Django 1.3, I have this working properly:

in settings.py:

USE_I18N = True
USE_L10N = True
TIME_ZONE = 'Europe/Amsterdam'
LANGUAGE_CODE = 'nl_NL'
FORMAT_MODULE_PATH = 'settings.locale'

In settings/locale/nl/formats.py:

DATETIME_FORMAT = 'j F Y \o\m H:i'


回答2:

I couldn't make it work using the FORMAT_MODULE_PATH setting, but I have managed to this using formats.get_format('DATE_INPUT_FORMATS')[0]. You can find this in my answer.