Ticket #14290: ticket14290.diff

File ticket14290.diff, 9.1 KB (added by Anssi Kääriäinen, 14 years ago)

For SVN HEAD

  • django/template/defaultfilters.py

    diff --git a/django/template/defaultfilters.py b/django/template/defaultfilters.py
    index 1500a05..3d1bff4 100644
    a b def date(value, arg=None):  
    706706        arg = settings.DATE_FORMAT
    707707    try:
    708708        return formats.date_format(value, arg)
    709     except AttributeError:
     709    except (AttributeError, UnicodeEncodeError):
    710710        try:
    711711            return format(value, arg)
    712712        except AttributeError:
    def time(value, arg=None):  
    722722        arg = settings.TIME_FORMAT
    723723    try:
    724724        return formats.time_format(value, arg)
    725     except AttributeError:
     725    except (AttributeError, UnicodeEncodeError):
    726726        try:
    727727            return dateformat.time_format(value, arg)
    728728        except AttributeError:
  • django/utils/encoding.py

    diff --git a/django/utils/encoding.py b/django/utils/encoding.py
    index e2d7249..9301419 100644
    a b def force_unicode(s, encoding='utf-8', strings_only=False, errors='strict'):  
    5858
    5959    If strings_only is True, don't convert (some) non-string-like objects.
    6060    """
     61    # Handle the common case first, saves 30-40% in performance when s
     62    # is an instance of unicode. This function gets called often in that
     63    # setting.
     64    if isinstance(s, unicode):
     65        return s
    6166    if strings_only and is_protected_type(s):
    6267        return s
    6368    try:
  • django/utils/formats.py

    diff --git a/django/utils/formats.py b/django/utils/formats.py
    index 372998f..69c9fed 100644
    a b from django.utils.importlib import import_module  
    77from django.utils.encoding import smart_str
    88from django.utils import dateformat, numberformat, datetime_safe
    99
     10# These constants are here so that we don't need to construct a new string
     11# every time x_format is called.
     12DECIMAL_SEPARATOR = 'DECIMAL_SEPARATOR'
     13NUMBER_GROUPING = 'NUMBER_GROUPING'
     14THOUSAND_SEPARATOR = 'THOUSAND_SEPARATOR'
     15DATE_FORMAT = 'DATE_FORMAT'
     16TIME_FORMAT = 'TIME_FORMAT'
     17DATETIME_FORMAT = 'DATETIME_FORMAT'
     18DATE_INPUT_FORMATS = 'DATE_INPUT_FORMATS'
     19TIME_INPUT_FORMATS = 'TIME_INPUT_FORMATS'
     20DATETIME_INPUT_FORMATS = 'DATETIME_INPUT_FORMATS'
     21
     22# format_cache is a mapping from (format_type, lang) to the format string.
     23# By using the cache, it is possible to avoid running get_format_modules
     24# repeatedly.
     25_format_cache = {}
     26
    1027def get_format_modules(reverse=False):
    1128    """
    1229    Returns an iterator over the format modules found in the project and Django
    1330    """
     31    lang = get_language()
    1432    modules = []
    15     if not check_for_language(get_language()) or not settings.USE_L10N:
     33    if not check_for_language(lang) or not settings.USE_L10N:
    1634        return modules
    17     locale = to_locale(get_language())
     35    locale = to_locale(lang)
    1836    if settings.FORMAT_MODULE_PATH:
    1937        format_locations = [settings.FORMAT_MODULE_PATH + '.%s']
    2038    else:
    def get_format_modules(reverse=False):  
    3452        modules.reverse()
    3553    return modules
    3654
    37 def get_format(format_type):
     55def get_format(format_type, lang=None):
    3856    """
    3957    For a specific format type, returns the format for the current
    4058    language (locale), defaults to the format in the settings.
    4159    format_type is the name of the format, e.g. 'DATE_FORMAT'
    4260    """
    43     format_type = smart_str(format_type)
     61    global _format_cache
    4462    if settings.USE_L10N:
    45         for module in get_format_modules():
    46             try:
    47                 return getattr(module, format_type)
    48             except AttributeError:
    49                 pass
     63        if lang is None:
     64            lang = get_language()
     65        try:
     66            return _format_cache[(format_type, lang)] \
     67                or getattr(settings, format_type)
     68        except KeyError:
     69            for module in get_format_modules():
     70                try:
     71                    val = getattr(module, format_type)
     72                    _format_cache[(format_type, lang)] = val
     73                    return val
     74                except AttributeError:
     75                    pass
     76            _format_cache[(format_type, lang)] = None
    5077    return getattr(settings, format_type)
    5178
    5279def date_format(value, format=None):
    def date_format(value, format=None):  
    5481    Formats a datetime.date or datetime.datetime object using a
    5582    localizable format
    5683    """
    57     return dateformat.format(value, get_format(format or 'DATE_FORMAT'))
     84    return dateformat.format(value, get_format(format or DATE_FORMAT))
    5885
    5986def time_format(value, format=None):
    6087    """
    6188    Formats a datetime.time object using a localizable format
    6289    """
    63     return dateformat.time_format(value, get_format(format or 'TIME_FORMAT'))
     90    return dateformat.time_format(value, get_format(format or TIME_FORMAT))
    6491
    6592def number_format(value, decimal_pos=None):
    6693    """
    6794    Formats a numeric value using localization settings
    6895    """
     96    lang = None
     97    if settings.USE_I18N:
     98        lang = get_language()
    6999    return numberformat.format(
    70100        value,
    71         get_format('DECIMAL_SEPARATOR'),
     101        get_format(DECIMAL_SEPARATOR, lang),
    72102        decimal_pos,
    73         get_format('NUMBER_GROUPING'),
    74         get_format('THOUSAND_SEPARATOR'),
     103        get_format(NUMBER_GROUPING, lang),
     104        get_format(THOUSAND_SEPARATOR, lang),
    75105    )
    76106
    77107def localize(value):
    def localize(value):  
    82112    if isinstance(value, (decimal.Decimal, float, int)):
    83113        return number_format(value)
    84114    elif isinstance(value, datetime.datetime):
    85         return date_format(value, 'DATETIME_FORMAT')
     115        return date_format(value, DATETIME_FORMAT)
    86116    elif isinstance(value, datetime.date):
    87117        return date_format(value)
    88118    elif isinstance(value, datetime.time):
    89         return time_format(value, 'TIME_FORMAT')
     119        return time_format(value, TIME_FORMAT)
    90120    else:
    91121        return value
    92122
    def localize_input(value, default=None):  
    99129        return number_format(value)
    100130    if isinstance(value, datetime.datetime):
    101131        value = datetime_safe.new_datetime(value)
    102         format = smart_str(default or get_format('DATETIME_INPUT_FORMATS')[0])
     132        format = smart_str(default or get_format(DATETIME_INPUT_FORMATS)[0])
    103133        return value.strftime(format)
    104134    elif isinstance(value, datetime.date):
    105135        value = datetime_safe.new_date(value)
    106         format = smart_str(default or get_format('DATE_INPUT_FORMATS')[0])
     136        format = smart_str(default or get_format(DATE_INPUT_FORMATS)[0])
    107137        return value.strftime(format)
    108138    elif isinstance(value, datetime.time):
    109         format = smart_str(default or get_format('TIME_INPUT_FORMATS')[0])
     139        format = smart_str(default or get_format(TIME_INPUT_FORMATS)[0])
    110140        return value.strftime(format)
    111141    return value
    112142
    def sanitize_separators(value):  
    116146    thousand separator setting. Used with form field input.
    117147    """
    118148    if settings.USE_L10N:
    119         decimal_separator = get_format('DECIMAL_SEPARATOR')
     149        decimal_separator = get_format(DECIMAL_SEPARATOR)
    120150        if isinstance(value, basestring):
    121151            parts = []
    122152            if decimal_separator in value:
    123153                value, decimals = value.split(decimal_separator, 1)
    124154                parts.append(decimals)
    125155            if settings.USE_THOUSAND_SEPARATOR:
    126                 parts.append(value.replace(get_format('THOUSAND_SEPARATOR'), ''))
     156                parts.append(value.replace(get_format(THOUSAND_SEPARATOR), ''))
    127157            else:
    128158                parts.append(value)
    129159            value = '.'.join(reversed(parts))
  • django/utils/numberformat.py

    diff --git a/django/utils/numberformat.py b/django/utils/numberformat.py
    index 129c27f..d6dbef8 100644
    a b  
    11from django.conf import settings
     2from django.utils.safestring import mark_safe
     3
    24
    35def format(number, decimal_sep, decimal_pos, grouping=0, thousand_sep=''):
    46    """
    def format(number, decimal_sep, decimal_pos, grouping=0, thousand_sep=''):  
    1113    * thousand_sep: Thousand separator symbol (for example ",")
    1214
    1315    """
     16    use_grouping = settings.USE_L10N and settings.USE_THOUSAND_SEPARATOR \
     17                   and grouping
     18    # Make the common case fast:
     19    if isinstance(number, int) and not use_grouping and not decimal_pos:
     20        return mark_safe(unicode(number))
    1421    # sign
    1522    if float(number) < 0:
    1623        sign = '-'
    1724    else:
    1825        sign = ''
    19     # decimal part
    2026    str_number = unicode(number)
    2127    if str_number[0] == '-':
    2228        str_number = str_number[1:]
     29    # decimal part
    2330    if '.' in str_number:
    2431        int_part, dec_part = str_number.split('.')
    2532        if decimal_pos:
    def format(number, decimal_sep, decimal_pos, grouping=0, thousand_sep=''):  
    3037        dec_part = dec_part + ('0' * (decimal_pos - len(dec_part)))
    3138    if dec_part: dec_part = decimal_sep + dec_part
    3239    # grouping
    33     if settings.USE_L10N and settings.USE_THOUSAND_SEPARATOR and grouping:
     40    if use_grouping:
    3441        int_part_gd = ''
    3542        for cnt, digit in enumerate(int_part[::-1]):
    3643            if cnt and not cnt % grouping:
    3744                int_part_gd += thousand_sep
    3845            int_part_gd += digit
    3946        int_part = int_part_gd[::-1]
    40 
    4147    return sign + int_part + dec_part
    4248
Back to Top