Outre la traduction d’un texte d’un language à l’autre (c’est à dire la localisation, abrégé l10n), on veut également ajouter de l’internationalisation (abrégé i18n), de sorte que l’application puisse être utilisée n’importe où dans le monde. Il va donc falloir prendre en compte un ensemble plus large de règles que le language, par exemple:
Activer la localisation:
www/core/settings/defaults.py
USE_L10N = True
FORMAT_MODULE_PATH = (
'core.formats',
)
Déclarer les formats des différents languages
www/core/formats/en/formats.py
SHORT_YEAR_MONTH_FORMAT = 'Y/m'
NUMERIC_DATE_FORMAT = 'm/d/Y'
NUMERIC_DATETIME_FORMAT = 'm/d/Y H:i:s'
CONDENSED_FILENAME_DATE_FORMAT = 'ymd'
FULL_MONTH_YEAR_FORMAT = 'F Y'
CONDENSED_MONTH_YEAR_FORMAT = 'b y'
NUMERIC_UNIT_SEPARATOR = '\xa0'
www/core/formats/fr/formats.py
SHORT_YEAR_MONTH_FORMAT = 'm/Y'
NUMERIC_DATE_FORMAT = 'd/m/Y'
NUMERIC_DATETIME_FORMAT = 'd/m/Y H:i:s'
CONDENSED_FILENAME_DATE_FORMAT = 'dmy'
FULL_MONTH_YEAR_FORMAT = 'F Y'
CONDENSED_MONTH_YEAR_FORMAT = 'b y'
NUMERIC_UNIT_SEPARATOR = '\xa0'
On utilise django.utils.formats
pour formatter des dates et nombres
def get_imc(instance, field, data):
return _('IMC : {}').format(
formats.localize(data, use_l10n=True)
)
separator = formats.get_format('NUMERIC_UNIT_SEPARATOR')
today = datetime.date.today()
now = datetime.datetime.now()
# 2022
print(formats.date_format(today, 'Y'))
# 12/2022
print(formats.date_format(today, 'SHORT_YEAR_MONTH_FORMAT'))
# décembre 2022
print(formats.date_format(today, 'FULL_MONTH_YEAR_FORMAT'))
# déc 22
print(formats.date_format(today, 'CONDENSED_MONTH_YEAR_FORMAT'))
# 26/12/2022
print(formats.date_format(today, 'NUMERIC_DATE_FORMAT'))
# lundi 26 décembre 2022
print(formats.date_format(today, 'l d F Y', use_l10n=False,))
# 26/12/2022 24:59:59
print(formats.date_format(now, 'NUMERIC_DATETIME_FORMAT'))
# 24:59
print(formats.date_format(now, 'TIME_FORMAT'))
# 26 déc. 2022 24:59
print(formats.date_format(now, 'SHORT_DATETIME_FORMAT'))
from django.template.defaultfilters import filesizeformat
class File(models.Model):
fileinput_size = models.PositiveIntegerField(
editable=False,
)
@property
def fileinput_size_formatted(self):
return filesizeformat(self.fileinput_size)
activate
permet de changer le format utilisé, exactement comme pour le changement de langue
www/core/tests/test_environment.py
import datetime
from django.utils.translation import activate
from django.test import TestCase
from django.utils import formats
class EnvironmentTest(TestCase):
def test_formats(self):
date = datetime.date(2020, 12, 30)
activate('en')
self.assertEqual(
formats.date_format(date, 'NUMERIC_DATE_FORMAT'),
'12/30/2020'
)
activate('fr')
self.assertEqual(
formats.date_format(date, 'NUMERIC_DATE_FORMAT'),
'30/12/2020'
)