2009-12-23 01:58:49 +08:00
|
|
|
import datetime
|
2015-01-28 20:35:27 +08:00
|
|
|
import decimal
|
2021-05-10 21:39:50 +08:00
|
|
|
import functools
|
|
|
|
import re
|
2013-02-15 23:37:52 +08:00
|
|
|
import unicodedata
|
2015-01-28 20:35:27 +08:00
|
|
|
from importlib import import_module
|
2009-12-23 01:58:49 +08:00
|
|
|
|
|
|
|
from django.conf import settings
|
2021-05-10 21:39:50 +08:00
|
|
|
from django.utils import dateformat, numberformat
|
2011-05-02 00:14:57 +08:00
|
|
|
from django.utils.functional import lazy
|
2015-01-28 20:35:27 +08:00
|
|
|
from django.utils.translation import (
|
|
|
|
check_for_language, get_language, to_locale,
|
|
|
|
)
|
2009-12-23 01:58:49 +08:00
|
|
|
|
2010-09-27 23:25:08 +08:00
|
|
|
# format_cache is a mapping from (format_type, lang) to the format string.
|
|
|
|
# By using the cache, it is possible to avoid running get_format_modules
|
|
|
|
# repeatedly.
|
|
|
|
_format_cache = {}
|
|
|
|
_format_modules_cache = {}
|
|
|
|
|
2012-10-13 18:21:35 +08:00
|
|
|
ISO_INPUT_FORMATS = {
|
2015-01-22 00:55:57 +08:00
|
|
|
'DATE_INPUT_FORMATS': ['%Y-%m-%d'],
|
|
|
|
'TIME_INPUT_FORMATS': ['%H:%M:%S', '%H:%M:%S.%f', '%H:%M'],
|
|
|
|
'DATETIME_INPUT_FORMATS': [
|
2012-10-13 18:21:35 +08:00
|
|
|
'%Y-%m-%d %H:%M:%S',
|
|
|
|
'%Y-%m-%d %H:%M:%S.%f',
|
|
|
|
'%Y-%m-%d %H:%M',
|
|
|
|
'%Y-%m-%d'
|
2015-01-22 00:55:57 +08:00
|
|
|
],
|
2012-10-13 18:21:35 +08:00
|
|
|
}
|
|
|
|
|
2013-11-03 07:53:29 +08:00
|
|
|
|
2015-11-12 03:10:55 +08:00
|
|
|
FORMAT_SETTINGS = frozenset([
|
|
|
|
'DECIMAL_SEPARATOR',
|
|
|
|
'THOUSAND_SEPARATOR',
|
|
|
|
'NUMBER_GROUPING',
|
|
|
|
'FIRST_DAY_OF_WEEK',
|
|
|
|
'MONTH_DAY_FORMAT',
|
|
|
|
'TIME_FORMAT',
|
|
|
|
'DATE_FORMAT',
|
|
|
|
'DATETIME_FORMAT',
|
|
|
|
'SHORT_DATE_FORMAT',
|
|
|
|
'SHORT_DATETIME_FORMAT',
|
|
|
|
'YEAR_MONTH_FORMAT',
|
|
|
|
'DATE_INPUT_FORMATS',
|
|
|
|
'TIME_INPUT_FORMATS',
|
|
|
|
'DATETIME_INPUT_FORMATS',
|
|
|
|
])
|
|
|
|
|
|
|
|
|
2011-02-04 21:52:36 +08:00
|
|
|
def reset_format_cache():
|
|
|
|
"""Clear any cached formats.
|
|
|
|
|
|
|
|
This method is provided primarily for testing purposes,
|
|
|
|
so that the effects of cached formats can be removed.
|
|
|
|
"""
|
|
|
|
global _format_cache, _format_modules_cache
|
|
|
|
_format_cache = {}
|
|
|
|
_format_modules_cache = {}
|
|
|
|
|
2013-11-03 07:53:29 +08:00
|
|
|
|
2013-09-07 06:01:23 +08:00
|
|
|
def iter_format_modules(lang, format_module_path=None):
|
2017-01-25 04:32:33 +08:00
|
|
|
"""Find format modules."""
|
2014-05-19 13:23:45 +08:00
|
|
|
if not check_for_language(lang):
|
|
|
|
return
|
|
|
|
|
|
|
|
if format_module_path is None:
|
|
|
|
format_module_path = settings.FORMAT_MODULE_PATH
|
|
|
|
|
|
|
|
format_locations = []
|
|
|
|
if format_module_path:
|
2016-12-29 23:27:49 +08:00
|
|
|
if isinstance(format_module_path, str):
|
2014-05-19 13:23:45 +08:00
|
|
|
format_module_path = [format_module_path]
|
|
|
|
for path in format_module_path:
|
|
|
|
format_locations.append(path + '.%s')
|
|
|
|
format_locations.append('django.conf.locale.%s')
|
|
|
|
locale = to_locale(lang)
|
|
|
|
locales = [locale]
|
|
|
|
if '_' in locale:
|
|
|
|
locales.append(locale.split('_')[0])
|
|
|
|
for location in format_locations:
|
|
|
|
for loc in locales:
|
2017-09-07 20:16:21 +08:00
|
|
|
try:
|
2014-05-19 13:23:45 +08:00
|
|
|
yield import_module('%s.formats' % (location % loc))
|
2017-09-07 20:16:21 +08:00
|
|
|
except ImportError:
|
|
|
|
pass
|
2010-09-27 23:25:08 +08:00
|
|
|
|
2013-11-03 07:53:29 +08:00
|
|
|
|
2021-07-18 21:06:30 +08:00
|
|
|
def get_format_modules(lang=None):
|
2017-01-25 04:32:33 +08:00
|
|
|
"""Return a list of the format modules found."""
|
2011-09-22 23:04:27 +08:00
|
|
|
if lang is None:
|
|
|
|
lang = get_language()
|
2015-12-27 04:11:53 +08:00
|
|
|
if lang not in _format_modules_cache:
|
|
|
|
_format_modules_cache[lang] = list(iter_format_modules(lang, settings.FORMAT_MODULE_PATH))
|
2021-07-18 21:06:30 +08:00
|
|
|
return _format_modules_cache[lang]
|
2009-12-23 01:58:49 +08:00
|
|
|
|
2013-11-03 07:53:29 +08:00
|
|
|
|
2010-10-30 00:48:58 +08:00
|
|
|
def get_format(format_type, lang=None, use_l10n=None):
|
2009-12-23 01:58:49 +08:00
|
|
|
"""
|
2017-01-25 04:32:33 +08:00
|
|
|
For a specific format type, return the format for the current
|
|
|
|
language (locale). Default to the format in the settings.
|
|
|
|
format_type is the name of the format, e.g. 'DATE_FORMAT'.
|
2010-10-30 00:48:58 +08:00
|
|
|
|
2017-01-25 04:32:33 +08:00
|
|
|
If use_l10n is provided and is not None, it forces the value to
|
2010-10-30 00:48:58 +08:00
|
|
|
be localized (or not), overriding the value of settings.USE_L10N.
|
2009-12-23 01:58:49 +08:00
|
|
|
"""
|
2021-09-09 13:42:05 +08:00
|
|
|
use_l10n = use_l10n or (use_l10n is None and (
|
|
|
|
settings._USE_L10N_INTERNAL
|
|
|
|
if hasattr(settings, '_USE_L10N_INTERNAL')
|
|
|
|
else settings.USE_L10N
|
|
|
|
))
|
2016-12-02 04:41:22 +08:00
|
|
|
if use_l10n and lang is None:
|
|
|
|
lang = get_language()
|
|
|
|
cache_key = (format_type, lang)
|
2017-09-07 20:16:21 +08:00
|
|
|
try:
|
2016-12-02 04:41:22 +08:00
|
|
|
return _format_cache[cache_key]
|
2017-09-07 20:16:21 +08:00
|
|
|
except KeyError:
|
|
|
|
pass
|
2016-12-02 04:41:22 +08:00
|
|
|
|
|
|
|
# The requested format_type has not been cached yet. Try to find it in any
|
|
|
|
# of the format_modules for the given lang if l10n is enabled. If it's not
|
|
|
|
# there or if l10n is disabled, fall back to the project settings.
|
|
|
|
val = None
|
|
|
|
if use_l10n:
|
|
|
|
for module in get_format_modules(lang):
|
2017-03-09 23:17:41 +08:00
|
|
|
val = getattr(module, format_type, None)
|
|
|
|
if val is not None:
|
|
|
|
break
|
2016-12-02 04:41:22 +08:00
|
|
|
if val is None:
|
|
|
|
if format_type not in FORMAT_SETTINGS:
|
|
|
|
return format_type
|
|
|
|
val = getattr(settings, format_type)
|
2017-05-28 07:08:46 +08:00
|
|
|
elif format_type in ISO_INPUT_FORMATS:
|
2016-12-02 04:41:22 +08:00
|
|
|
# If a list of input formats from one of the format_modules was
|
|
|
|
# retrieved, make sure the ISO_INPUT_FORMATS are in this list.
|
|
|
|
val = list(val)
|
|
|
|
for iso_input in ISO_INPUT_FORMATS.get(format_type, ()):
|
|
|
|
if iso_input not in val:
|
|
|
|
val.append(iso_input)
|
|
|
|
_format_cache[cache_key] = val
|
|
|
|
return val
|
2009-12-23 01:58:49 +08:00
|
|
|
|
2016-11-13 01:11:23 +08:00
|
|
|
|
2016-12-29 23:27:49 +08:00
|
|
|
get_format_lazy = lazy(get_format, str, list, tuple)
|
2011-05-02 00:14:57 +08:00
|
|
|
|
2013-11-03 07:53:29 +08:00
|
|
|
|
2010-10-30 00:48:58 +08:00
|
|
|
def date_format(value, format=None, use_l10n=None):
|
2009-12-23 01:58:49 +08:00
|
|
|
"""
|
2017-01-25 04:32:33 +08:00
|
|
|
Format a datetime.date or datetime.datetime object using a
|
|
|
|
localizable format.
|
2010-10-30 00:48:58 +08:00
|
|
|
|
|
|
|
If use_l10n is provided and is not None, that will force the value to
|
|
|
|
be localized (or not), overriding the value of settings.USE_L10N.
|
2009-12-23 01:58:49 +08:00
|
|
|
"""
|
2010-10-30 00:48:58 +08:00
|
|
|
return dateformat.format(value, get_format(format or 'DATE_FORMAT', use_l10n=use_l10n))
|
2009-12-23 01:58:49 +08:00
|
|
|
|
2013-11-03 07:53:29 +08:00
|
|
|
|
2010-10-30 00:48:58 +08:00
|
|
|
def time_format(value, format=None, use_l10n=None):
|
2010-01-02 05:36:36 +08:00
|
|
|
"""
|
2017-01-25 04:32:33 +08:00
|
|
|
Format a datetime.time object using a localizable format.
|
2010-10-30 00:48:58 +08:00
|
|
|
|
2017-01-25 04:32:33 +08:00
|
|
|
If use_l10n is provided and is not None, it forces the value to
|
2010-10-30 00:48:58 +08:00
|
|
|
be localized (or not), overriding the value of settings.USE_L10N.
|
2010-01-02 05:36:36 +08:00
|
|
|
"""
|
2010-10-30 00:48:58 +08:00
|
|
|
return dateformat.time_format(value, get_format(format or 'TIME_FORMAT', use_l10n=use_l10n))
|
2010-01-02 05:36:36 +08:00
|
|
|
|
2013-11-03 07:53:29 +08:00
|
|
|
|
2011-09-08 21:25:11 +08:00
|
|
|
def number_format(value, decimal_pos=None, use_l10n=None, force_grouping=False):
|
2009-12-23 01:58:49 +08:00
|
|
|
"""
|
2017-01-25 04:32:33 +08:00
|
|
|
Format a numeric value using localization settings.
|
2010-10-30 00:48:58 +08:00
|
|
|
|
2017-01-25 04:32:33 +08:00
|
|
|
If use_l10n is provided and is not None, it forces the value to
|
2010-10-30 00:48:58 +08:00
|
|
|
be localized (or not), overriding the value of settings.USE_L10N.
|
2009-12-23 01:58:49 +08:00
|
|
|
"""
|
2021-09-09 13:42:05 +08:00
|
|
|
use_l10n = use_l10n or (use_l10n is None and (
|
|
|
|
settings._USE_L10N_INTERNAL
|
|
|
|
if hasattr(settings, '_USE_L10N_INTERNAL')
|
|
|
|
else settings.USE_L10N
|
|
|
|
))
|
2021-06-05 18:46:13 +08:00
|
|
|
lang = get_language() if use_l10n else None
|
2009-12-23 01:58:49 +08:00
|
|
|
return numberformat.format(
|
|
|
|
value,
|
2010-10-30 00:48:58 +08:00
|
|
|
get_format('DECIMAL_SEPARATOR', lang, use_l10n=use_l10n),
|
2009-12-23 01:58:49 +08:00
|
|
|
decimal_pos,
|
2010-10-30 00:48:58 +08:00
|
|
|
get_format('NUMBER_GROUPING', lang, use_l10n=use_l10n),
|
|
|
|
get_format('THOUSAND_SEPARATOR', lang, use_l10n=use_l10n),
|
2018-07-20 04:44:40 +08:00
|
|
|
force_grouping=force_grouping,
|
|
|
|
use_l10n=use_l10n,
|
2009-12-23 01:58:49 +08:00
|
|
|
)
|
|
|
|
|
2013-11-03 07:53:29 +08:00
|
|
|
|
2010-10-30 00:48:58 +08:00
|
|
|
def localize(value, use_l10n=None):
|
2009-12-23 01:58:49 +08:00
|
|
|
"""
|
2017-01-25 04:32:33 +08:00
|
|
|
Check if value is a localizable type (date, number...) and return it
|
2010-10-30 00:48:58 +08:00
|
|
|
formatted as a string using current locale format.
|
|
|
|
|
2017-01-25 04:32:33 +08:00
|
|
|
If use_l10n is provided and is not None, it forces the value to
|
2010-10-30 00:48:58 +08:00
|
|
|
be localized (or not), overriding the value of settings.USE_L10N.
|
2009-12-23 01:58:49 +08:00
|
|
|
"""
|
2016-12-29 23:27:49 +08:00
|
|
|
if isinstance(value, str): # Handle strings first for performance reasons.
|
2015-11-12 21:59:37 +08:00
|
|
|
return value
|
|
|
|
elif isinstance(value, bool): # Make sure booleans don't get treated as numbers
|
2017-10-22 18:10:27 +08:00
|
|
|
return str(value)
|
2016-12-29 23:27:49 +08:00
|
|
|
elif isinstance(value, (decimal.Decimal, float, int)):
|
2020-06-04 15:11:37 +08:00
|
|
|
if use_l10n is False:
|
|
|
|
return str(value)
|
2010-10-30 00:48:58 +08:00
|
|
|
return number_format(value, use_l10n=use_l10n)
|
2010-09-13 03:40:44 +08:00
|
|
|
elif isinstance(value, datetime.datetime):
|
2010-10-30 00:48:58 +08:00
|
|
|
return date_format(value, 'DATETIME_FORMAT', use_l10n=use_l10n)
|
2010-09-13 03:40:44 +08:00
|
|
|
elif isinstance(value, datetime.date):
|
2010-10-30 00:48:58 +08:00
|
|
|
return date_format(value, use_l10n=use_l10n)
|
2010-09-13 03:40:44 +08:00
|
|
|
elif isinstance(value, datetime.time):
|
2010-10-30 00:48:58 +08:00
|
|
|
return time_format(value, 'TIME_FORMAT', use_l10n=use_l10n)
|
2015-11-12 21:59:37 +08:00
|
|
|
return value
|
2009-12-23 01:58:49 +08:00
|
|
|
|
2013-11-03 07:53:29 +08:00
|
|
|
|
2009-12-31 06:11:48 +08:00
|
|
|
def localize_input(value, default=None):
|
|
|
|
"""
|
2017-01-25 04:32:33 +08:00
|
|
|
Check if an input value is a localizable type and return it
|
2009-12-31 06:11:48 +08:00
|
|
|
formatted with the appropriate formatting string of the current locale.
|
|
|
|
"""
|
2016-12-29 23:27:49 +08:00
|
|
|
if isinstance(value, str): # Handle strings first for performance reasons.
|
2015-11-12 21:59:37 +08:00
|
|
|
return value
|
2016-02-03 22:59:55 +08:00
|
|
|
elif isinstance(value, bool): # Don't treat booleans as numbers.
|
2016-12-29 23:27:49 +08:00
|
|
|
return str(value)
|
|
|
|
elif isinstance(value, (decimal.Decimal, float, int)):
|
2010-02-05 08:44:35 +08:00
|
|
|
return number_format(value)
|
2010-09-27 23:25:08 +08:00
|
|
|
elif isinstance(value, datetime.datetime):
|
2017-01-12 06:17:25 +08:00
|
|
|
format = default or get_format('DATETIME_INPUT_FORMATS')[0]
|
2021-05-10 21:39:50 +08:00
|
|
|
format = sanitize_strftime_format(format)
|
2009-12-31 06:11:48 +08:00
|
|
|
return value.strftime(format)
|
|
|
|
elif isinstance(value, datetime.date):
|
2017-01-12 06:17:25 +08:00
|
|
|
format = default or get_format('DATE_INPUT_FORMATS')[0]
|
2021-05-10 21:39:50 +08:00
|
|
|
format = sanitize_strftime_format(format)
|
2009-12-31 06:11:48 +08:00
|
|
|
return value.strftime(format)
|
|
|
|
elif isinstance(value, datetime.time):
|
2017-01-12 06:17:25 +08:00
|
|
|
format = default or get_format('TIME_INPUT_FORMATS')[0]
|
2009-12-31 06:11:48 +08:00
|
|
|
return value.strftime(format)
|
|
|
|
return value
|
2010-03-01 18:19:24 +08:00
|
|
|
|
2013-11-03 07:53:29 +08:00
|
|
|
|
2021-09-27 15:10:58 +08:00
|
|
|
@functools.lru_cache
|
2021-05-10 21:39:50 +08:00
|
|
|
def sanitize_strftime_format(fmt):
|
|
|
|
"""
|
|
|
|
Ensure that certain specifiers are correctly padded with leading zeros.
|
|
|
|
|
|
|
|
For years < 1000 specifiers %C, %F, %G, and %Y don't work as expected for
|
|
|
|
strftime provided by glibc on Linux as they don't pad the year or century
|
|
|
|
with leading zeros. Support for specifying the padding explicitly is
|
|
|
|
available, however, which can be used to fix this issue.
|
|
|
|
|
|
|
|
FreeBSD, macOS, and Windows do not support explicitly specifying the
|
|
|
|
padding, but return four digit years (with leading zeros) as expected.
|
|
|
|
|
|
|
|
This function checks whether the %Y produces a correctly padded string and,
|
|
|
|
if not, makes the following substitutions:
|
|
|
|
|
|
|
|
- %C → %02C
|
|
|
|
- %F → %010F
|
|
|
|
- %G → %04G
|
|
|
|
- %Y → %04Y
|
|
|
|
|
|
|
|
See https://bugs.python.org/issue13305 for more details.
|
|
|
|
"""
|
|
|
|
if datetime.date(1, 1, 1).strftime('%Y') == '0001':
|
|
|
|
return fmt
|
|
|
|
mapping = {'C': 2, 'F': 10, 'G': 4, 'Y': 4}
|
|
|
|
return re.sub(
|
|
|
|
r'((?:^|[^%])(?:%%)*)%([CFGY])',
|
|
|
|
lambda m: r'%s%%0%s%s' % (m[1], mapping[m[2]], m[2]),
|
|
|
|
fmt,
|
|
|
|
)
|
|
|
|
|
|
|
|
|
2010-03-01 18:19:24 +08:00
|
|
|
def sanitize_separators(value):
|
|
|
|
"""
|
2017-01-25 04:32:33 +08:00
|
|
|
Sanitize a value according to the current decimal and
|
2010-03-01 18:19:24 +08:00
|
|
|
thousand separator setting. Used with form field input.
|
|
|
|
"""
|
2017-04-06 23:34:00 +08:00
|
|
|
if isinstance(value, str):
|
2013-02-15 23:37:52 +08:00
|
|
|
parts = []
|
2010-03-01 18:19:24 +08:00
|
|
|
decimal_separator = get_format('DECIMAL_SEPARATOR')
|
2013-02-15 23:37:52 +08:00
|
|
|
if decimal_separator in value:
|
|
|
|
value, decimals = value.split(decimal_separator, 1)
|
|
|
|
parts.append(decimals)
|
|
|
|
if settings.USE_THOUSAND_SEPARATOR:
|
|
|
|
thousand_sep = get_format('THOUSAND_SEPARATOR')
|
2014-08-19 01:57:50 +08:00
|
|
|
if thousand_sep == '.' and value.count('.') == 1 and len(value.split('.')[-1]) != 3:
|
|
|
|
# Special case where we suspect a dot meant decimal separator (see #22171)
|
|
|
|
pass
|
|
|
|
else:
|
2014-09-26 20:31:50 +08:00
|
|
|
for replacement in {
|
|
|
|
thousand_sep, unicodedata.normalize('NFKD', thousand_sep)}:
|
2014-08-19 01:57:50 +08:00
|
|
|
value = value.replace(replacement, '')
|
2013-02-15 23:37:52 +08:00
|
|
|
parts.append(value)
|
|
|
|
value = '.'.join(reversed(parts))
|
2010-03-01 18:19:24 +08:00
|
|
|
return value
|