Ticket #7980: i18n_simple.diff

File i18n_simple.diff, 79.4 KB (added by garcia_marc, 6 years ago)

diff of all work developed on the [soc2009/i18n] with .po and formats files removed

  • django/conf/global_settings.py

     
     1# -*- encoding: utf-8 -*-
    12# Default Django settings. Override these with settings in the module
    23# pointed-to by the DJANGO_SETTINGS_MODULE environment variable.
    34
     
    7576    ('lt', gettext_noop('Lithuanian')),
    7677    ('mk', gettext_noop('Macedonian')),
    7778    ('nl', gettext_noop('Dutch')),
    78     ('no', gettext_noop('Norwegian')),
     79    ('nb', gettext_noop(u'Norwegian Bokmål')),
    7980    ('pl', gettext_noop('Polish')),
    8081    ('pt', gettext_noop('Portuguese')),
    8182    ('pt-br', gettext_noop('Brazilian Portuguese')),
     
    103104LOCALE_PATHS = ()
    104105LANGUAGE_COOKIE_NAME = 'django_language'
    105106
     107# If you set this to True, Django will format dates, numbers and calendars
     108# according to user current locale
     109USE_FORMAT_I18N = False
     110
    106111# Not-necessarily-technical managers of the site. They get broken link
    107112# notifications and other various e-mails.
    108113MANAGERS = ADMINS
     
    255260# you'd pass directly to os.chmod; see http://docs.python.org/lib/os-file-dir.html.
    256261FILE_UPLOAD_PERMISSIONS = None
    257262
     263# Python module path where user will place custom format definition.
     264# The directory where this setting is pointing should contain subdirectories
     265# named as the locales, containing a formats.py file
     266# (i.e. "myproject.locale" for myproject/locale/en/formats.py etc. use)
     267FORMAT_MODULE_PATH = None
     268
    258269# Default formatting for date objects. See all available format strings here:
    259270# http://docs.djangoproject.com/en/dev/ref/templates/builtins/#now
    260271DATE_FORMAT = 'N j, Y'
     
    277288# http://docs.djangoproject.com/en/dev/ref/templates/builtins/#now
    278289MONTH_DAY_FORMAT = 'F j'
    279290
     291# Default shortformatting for date objects. See all available format strings here:
     292# http://docs.djangoproject.com/en/dev/ref/templates/builtins/#now
     293SHORT_DATE_FORMAT = 'm/d/Y'
     294
     295# Default short formatting for datetime objects.
     296# See all available format strings here:
     297# http://docs.djangoproject.com/en/dev/ref/templates/builtins/#now
     298SHORT_DATETIME_FORMAT = 'm/d/Y P'
     299
     300# Default formats tried to parse dates from input boxes
     301# These formats are tried in the specified order
     302# See all available format string here:
     303# http://docs.python.org/library/datetime.html#strftime-behavior
     304# * Note that these format strings are different from the ones to display dates
     305DATE_INPUT_FORMATS = (
     306    '%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', # '2006-10-25', '10/25/2006', '10/25/06'
     307    '%b %d %Y', '%b %d, %Y',            # 'Oct 25 2006', 'Oct 25, 2006'
     308    '%d %b %Y', '%d %b, %Y',            # '25 Oct 2006', '25 Oct, 2006'
     309    '%B %d %Y', '%B %d, %Y',            # 'October 25 2006', 'October 25, 2006'
     310    '%d %B %Y', '%d %B, %Y',            # '25 October 2006', '25 October, 2006'
     311)
     312
     313# Default formats tried to parse times from input boxes
     314# These formats are tried in the specified order
     315# See all available format string here:
     316# http://docs.python.org/library/datetime.html#strftime-behavior
     317# * Note that these format strings are different from the ones to display dates
     318TIME_INPUT_FORMATS = (
     319    '%H:%M:%S',     # '14:30:59'
     320    '%H:%M',        # '14:30'
     321)
     322
     323# Default formats tried to parse dates and times from input boxes
     324# These formats are tried in the specified order
     325# See all available format string here:
     326# http://docs.python.org/library/datetime.html#strftime-behavior
     327# * Note that these format strings are different from the ones to display dates
     328DATETIME_INPUT_FORMATS = (
     329    '%Y-%m-%d %H:%M:%S',     # '2006-10-25 14:30:59'
     330    '%Y-%m-%d %H:%M',        # '2006-10-25 14:30'
     331    '%Y-%m-%d',              # '2006-10-25'
     332    '%m/%d/%Y %H:%M:%S',     # '10/25/2006 14:30:59'
     333    '%m/%d/%Y %H:%M',        # '10/25/2006 14:30'
     334    '%m/%d/%Y',              # '10/25/2006'
     335    '%m/%d/%y %H:%M:%S',     # '10/25/06 14:30:59'
     336    '%m/%d/%y %H:%M',        # '10/25/06 14:30'
     337    '%m/%d/%y',              # '10/25/06'
     338)
     339
     340# First day of week, to be used on calendars
     341# 0 means Sunday, 1 means Monday...
     342FIRST_DAY_OF_WEEK = 0
     343
     344# Decimal separator symbol
     345DECIMAL_SEPARATOR = '.'
     346
     347# Boolean that sets whether to add thousand separator when formatting numbers
     348USE_THOUSAND_SEPARATOR = False
     349
     350# Number of digits that will be togheter, when spliting them by THOUSAND_SEPARATOR
     351# 0 means no grouping, 3 means splitting by thousands...
     352NUMBER_GROUPING = 0
     353
     354# Thousand separator symbol
     355THOUSAND_SEPARATOR = ','
     356
    280357# Do you want to manage transactions manually?
    281358# Hint: you really don't!
    282359TRANSACTIONS_MANAGED = False
  • django/forms/extras/widgets.py

     
    88from django.forms.widgets import Widget, Select
    99from django.utils.dates import MONTHS
    1010from django.utils.safestring import mark_safe
     11from django.utils.formats import getformat
     12from django.conf import settings
    1113
    1214__all__ = ('SelectDateWidget',)
    1315
     
    4547                if match:
    4648                    year_val, month_val, day_val = [int(v) for v in match.groups()]
    4749
     50        choices = [(i, i) for i in self.years]
     51        year_html = self.create_select(name, self.year_field, value, year_val, choices)
     52        choices = MONTHS.items()
     53        month_html = self.create_select(name, self.month_field, value, month_val, choices)
     54        choices = [(i, i) for i in range(1, 32)]
     55        day_html = self.create_select(name, self.day_field, value, day_val,  choices)
     56
     57        format = getformat('DATE_FORMAT')
     58        escaped = False
    4859        output = []
    49 
    50         if 'id' in self.attrs:
    51             id_ = self.attrs['id']
    52         else:
    53             id_ = 'id_%s' % name
    54 
    55         month_choices = MONTHS.items()
    56         if not (self.required and value):
    57             month_choices.append(self.none_value)
    58         month_choices.sort()
    59         local_attrs = self.build_attrs(id=self.month_field % id_)
    60         s = Select(choices=month_choices)
    61         select_html = s.render(self.month_field % name, month_val, local_attrs)
    62         output.append(select_html)
    63 
    64         day_choices = [(i, i) for i in range(1, 32)]
    65         if not (self.required and value):
    66             day_choices.insert(0, self.none_value)
    67         local_attrs['id'] = self.day_field % id_
    68         s = Select(choices=day_choices)
    69         select_html = s.render(self.day_field % name, day_val, local_attrs)
    70         output.append(select_html)
    71 
    72         year_choices = [(i, i) for i in self.years]
    73         if not (self.required and value):
    74             year_choices.insert(0, self.none_value)
    75         local_attrs['id'] = self.year_field % id_
    76         s = Select(choices=year_choices)
    77         select_html = s.render(self.year_field % name, year_val, local_attrs)
    78         output.append(select_html)
    79 
     60        for char in format:
     61            if escaped:
     62                escaped = False
     63            elif char == '\\':
     64                escaped = True
     65            elif char in 'Yy':
     66                output.append(year_html)
     67            elif char in 'bFMmNn':
     68                output.append(month_html)
     69            elif char in 'dj':
     70                output.append(day_html)
    8071        return mark_safe(u'\n'.join(output))
    8172
    8273    def id_for_label(self, id_):
     
    9081        if y == m == d == "0":
    9182            return None
    9283        if y and m and d:
    93             return '%s-%s-%s' % (y, m, d)
     84            if settings.USE_FORMAT_I18N:
     85                input_format = getformat('DATE_INPUT_FORMATS')[0]
     86                try:
     87                    date_value = datetime.date(int(y), int(m), int(d))
     88                except ValueError:
     89                    pass
     90                else:
     91                    return date_value.strftime(input_format)
     92            else:
     93                return '%s-%s-%s' % (y, m, d)
    9494        return data.get(name, None)
     95
     96    def create_select(self, name, field, value, val, choices):
     97        if 'id' in self.attrs:
     98            id_ = self.attrs['id']
     99        else:
     100            id_ = 'id_%s' % name
     101        if not (self.required and value):
     102            choices.insert(0, self.none_value)
     103        local_attrs = self.build_attrs(id=field % id_)
     104        s = Select(choices=choices)
     105        select_html = s.render(field % name, val, local_attrs)
     106        return select_html
     107
  • django/forms/fields.py

     
    2626import django.core.exceptions
    2727from django.utils.translation import ugettext_lazy as _
    2828from django.utils.encoding import smart_unicode, smart_str
     29from django.utils.formats import getformat
    2930
    3031from util import ErrorList, ValidationError
    3132from widgets import TextInput, PasswordInput, HiddenInput, MultipleHiddenInput, FileInput, CheckboxInput, Select, NullBooleanSelect, SelectMultiple, DateInput, DateTimeInput, TimeInput, SplitDateTimeWidget, SplitHiddenDateTimeWidget
     
    3334
    3435__all__ = (
    3536    'Field', 'CharField', 'IntegerField',
    36     'DEFAULT_DATE_INPUT_FORMATS', 'DateField',
    37     'DEFAULT_TIME_INPUT_FORMATS', 'TimeField',
    38     'DEFAULT_DATETIME_INPUT_FORMATS', 'DateTimeField', 'TimeField',
     37    'DateField', 'TimeField', 'DateTimeField', 'TimeField',
    3938    'RegexField', 'EmailField', 'FileField', 'ImageField', 'URLField',
    4039    'BooleanField', 'NullBooleanField', 'ChoiceField', 'MultipleChoiceField',
    4140    'ComboField', 'MultiValueField', 'FloatField', 'DecimalField',
     
    210209        if not self.required and value in EMPTY_VALUES:
    211210            return None
    212211        try:
    213             value = float(value)
     212            # We always accept dot as decimal separator
     213            if isinstance(value, str) or isinstance(value, unicode):
     214                value = float(value.replace(getformat('DECIMAL_SEPARATOR'), '.'))
    214215        except (ValueError, TypeError):
    215216            raise ValidationError(self.error_messages['invalid'])
    216217        if self.max_value is not None and value > self.max_value:
     
    246247            return None
    247248        value = smart_str(value).strip()
    248249        try:
    249             value = Decimal(value)
     250            # We always accept dot as decimal separator
     251            if isinstance(value, str) or isinstance(value, unicode):
     252                value = Decimal(value.replace(getformat('DECIMAL_SEPARATOR'), '.'))
    250253        except DecimalException:
    251254            raise ValidationError(self.error_messages['invalid'])
    252255
     
    274277            raise ValidationError(self.error_messages['max_whole_digits'] % (self.max_digits - self.decimal_places))
    275278        return value
    276279
    277 DEFAULT_DATE_INPUT_FORMATS = (
    278     '%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', # '2006-10-25', '10/25/2006', '10/25/06'
    279     '%b %d %Y', '%b %d, %Y',            # 'Oct 25 2006', 'Oct 25, 2006'
    280     '%d %b %Y', '%d %b, %Y',            # '25 Oct 2006', '25 Oct, 2006'
    281     '%B %d %Y', '%B %d, %Y',            # 'October 25 2006', 'October 25, 2006'
    282     '%d %B %Y', '%d %B, %Y',            # '25 October 2006', '25 October, 2006'
    283 )
    284 
    285280class DateField(Field):
    286281    widget = DateInput
    287282    default_error_messages = {
     
    290285
    291286    def __init__(self, input_formats=None, *args, **kwargs):
    292287        super(DateField, self).__init__(*args, **kwargs)
    293         self.input_formats = input_formats or DEFAULT_DATE_INPUT_FORMATS
     288        self.input_formats = input_formats
    294289
    295290    def clean(self, value):
    296291        """
     
    304299            return value.date()
    305300        if isinstance(value, datetime.date):
    306301            return value
    307         for format in self.input_formats:
     302        for format in self.input_formats or getformat('DATE_INPUT_FORMATS'):
    308303            try:
    309304                return datetime.date(*time.strptime(value, format)[:3])
    310305            except ValueError:
    311306                continue
    312307        raise ValidationError(self.error_messages['invalid'])
    313308
    314 DEFAULT_TIME_INPUT_FORMATS = (
    315     '%H:%M:%S',     # '14:30:59'
    316     '%H:%M',        # '14:30'
    317 )
    318 
    319309class TimeField(Field):
    320310    widget = TimeInput
    321311    default_error_messages = {
     
    324314
    325315    def __init__(self, input_formats=None, *args, **kwargs):
    326316        super(TimeField, self).__init__(*args, **kwargs)
    327         self.input_formats = input_formats or DEFAULT_TIME_INPUT_FORMATS
     317        self.input_formats = input_formats
    328318
    329319    def clean(self, value):
    330320        """
     
    336326            return None
    337327        if isinstance(value, datetime.time):
    338328            return value
    339         for format in self.input_formats:
     329        for format in self.input_formats or getformat('TIME_INPUT_FORMATS'):
    340330            try:
    341331                return datetime.time(*time.strptime(value, format)[3:6])
    342332            except ValueError:
    343333                continue
    344334        raise ValidationError(self.error_messages['invalid'])
    345335
    346 DEFAULT_DATETIME_INPUT_FORMATS = (
    347     '%Y-%m-%d %H:%M:%S',     # '2006-10-25 14:30:59'
    348     '%Y-%m-%d %H:%M',        # '2006-10-25 14:30'
    349     '%Y-%m-%d',              # '2006-10-25'
    350     '%m/%d/%Y %H:%M:%S',     # '10/25/2006 14:30:59'
    351     '%m/%d/%Y %H:%M',        # '10/25/2006 14:30'
    352     '%m/%d/%Y',              # '10/25/2006'
    353     '%m/%d/%y %H:%M:%S',     # '10/25/06 14:30:59'
    354     '%m/%d/%y %H:%M',        # '10/25/06 14:30'
    355     '%m/%d/%y',              # '10/25/06'
    356 )
    357 
    358336class DateTimeField(Field):
    359337    widget = DateTimeInput
    360338    default_error_messages = {
     
    363341
    364342    def __init__(self, input_formats=None, *args, **kwargs):
    365343        super(DateTimeField, self).__init__(*args, **kwargs)
    366         self.input_formats = input_formats or DEFAULT_DATETIME_INPUT_FORMATS
     344        self.input_formats = input_formats
    367345
    368346    def clean(self, value):
    369347        """
     
    383361            if len(value) != 2:
    384362                raise ValidationError(self.error_messages['invalid'])
    385363            value = '%s %s' % tuple(value)
    386         for format in self.input_formats:
     364        for format in self.input_formats or getformat('DATETIME_INPUT_FORMATS'):
    387365            try:
    388366                return datetime.datetime(*time.strptime(value, format)[:6])
    389367            except ValueError:
  • django/forms/widgets.py

     
    1515from django.utils.translation import ugettext
    1616from django.utils.encoding import StrAndUnicode, force_unicode
    1717from django.utils.safestring import mark_safe
     18from django.utils.formats import localize
    1819from django.utils import datetime_safe
    1920from datetime import time
    2021from util import flatatt
     
    213214        final_attrs = self.build_attrs(attrs, type=self.input_type, name=name)
    214215        if value != '':
    215216            # Only add the 'value' attribute if a value is non-empty.
    216             final_attrs['value'] = force_unicode(value)
     217            final_attrs['value'] = force_unicode(localize(value, is_input=True))
    217218        return mark_safe(u'<input%s />' % flatatt(final_attrs))
    218219
    219220class TextInput(Input):
  • django/core/management/commands/importcldr.py

     
     1import sys
     2import os
     3import re
     4from optparse import make_option, OptionParser
     5
     6from django.core.management.base import LabelCommand, CommandError
     7
     8try:
     9    from lxml import etree
     10except ImportError:
     11    raise CommandError('You need to install `python-lxml` to run this script')
     12
     13FORMATS_FILE_NAME = 'formats.py'
     14FORMATS_FILE_HEADER = '''# -*- encoding: utf-8 -*-
     15# This file is distributed under the same license as the Django package.
     16#
     17
     18'''
     19
     20def quote(nodes, name,  locale, previous):
     21    if len(nodes):
     22        return "'%s'" % unicode(nodes[0].text).replace("'", "\\'")
     23    else:
     24        return None
     25
     26def convert_time(nodes, name,  locale, previous):
     27    SPECIAL_CHARS = ('a', 'A', 'b', 'B', 'd', 'D', 'f', 'F', 'g', 'G', 'h',
     28        'H', 'i', 'I', 'j', 'l', 'L', 'm', 'M', 'n', 'N', 'O', 'P', 'r',
     29        's', 'S', 't', 'T', 'U', 'w', 'W', 'y', 'Y', 'z', 'Z')
     30    FORMAT_STR_MAP = ( # not using a dict, because we have to apply formats in order
     31        ('dd', 'd'),
     32        ('d', 'j'),
     33        ('MMMM', 'F'),
     34        ('MMM', 'M'),
     35        ('MM', 'm'),
     36        ('M', 'n'),
     37        ('yyyy', 'Y'),
     38        ('yy', 'y'),
     39        ('y', 'Y'),
     40        ('hh', 'h'),
     41        ('h', 'g'),
     42        ('HH', 'H'),
     43        ('H', 'G'),
     44        ('mm', 'i'),
     45        ('ss', 's'),
     46        ('a', 'A'),
     47        ('LLLL', 'F'),
     48    )
     49    if len(nodes):
     50        original = nodes[0].text
     51        result = ''
     52        for cnt, segment in enumerate(original.split("'")):
     53            if cnt % 2:
     54                for char in SPECIAL_CHARS:
     55                    segment = segment.replace(char, '\\%s' % char)
     56                result += segment
     57            else:
     58                while segment:
     59                    found = False
     60                    for src, dst in FORMAT_STR_MAP:
     61                        if segment[0:len(src)] == src:
     62                            result += dst
     63                            segment = segment[len(src):]
     64                            found = True
     65                            break
     66                    if not found:
     67                        result += segment[0]
     68                        segment = segment[1:]
     69
     70        return "'%s'" % result
     71    else:
     72        return None
     73
     74def datetime(nodes, name, locale, previous):
     75    result = None
     76    if len(nodes) and 'DATE_FORMAT' in previous and 'TIME_FORMAT' in previous:
     77        result = nodes[0].text
     78        result = result.replace('{0}', previous['TIME_FORMAT'][1:-1])
     79        if name == 'SHORT_DATETIME_FORMAT' and 'SHORT_DATE_FORMAT' in previous:
     80            result = result.replace('{1}', previous['SHORT_DATE_FORMAT'][1:-1])
     81        else:
     82            result = result.replace('{1}', previous['DATE_FORMAT'][1:-1])
     83    if result:
     84        return "'%s'" % result
     85    else:
     86        return None
     87
     88FORMATS_MAP = [
     89    {
     90        'name': 'DATE_FORMAT',
     91        'file': os.path.join('common', 'main', '%(locale)s.xml'),
     92        'pattern': "/ldml/dates/calendars/calendar[@type='gregorian']/dateFormats/dateFormatLength[@type='long']/dateFormat/pattern",
     93        'conversion': convert_time,
     94    },
     95    {
     96        'name': 'TIME_FORMAT',
     97        'file': os.path.join('common', 'main', '%(locale)s.xml'),
     98        'pattern': "/ldml/dates/calendars/calendar[@type='gregorian']/timeFormats/timeFormatLength[@type='medium']/timeFormat/pattern",
     99        'conversion': convert_time,
     100    },
     101    {
     102        'name': 'DATETIME_FORMAT',
     103        'file': os.path.join('common', 'main', '%(locale)s.xml'),
     104        'pattern': "/ldml/dates/calendars/calendar[@type='gregorian']/dateTimeFormats/dateTimeFormatLength[@type='long']/dateTimeFormat/pattern",
     105        'conversion': datetime,
     106    },
     107    {
     108        'name': 'YEAR_MONTH_FORMAT',
     109        'file': os.path.join('common', 'main', '%(locale)s.xml'),
     110        'pattern': "/ldml/dates/calendars/calendar[@type='gregorian']/dateTimeFormats/availableFormats/dateFormatItem[@id='yMMMM']",
     111        'conversion': convert_time,
     112    },
     113    {
     114        'name': 'MONTH_DAY_FORMAT',
     115        'file': os.path.join('common', 'main', '%(locale)s.xml'),
     116        'pattern': "/ldml/dates/calendars/calendar[@type='gregorian']/dateTimeFormats/availableFormats/dateFormatItem[@id='MMMMd']",
     117        'conversion': convert_time,
     118    },
     119    {
     120        'name': 'SHORT_DATE_FORMAT',
     121        'file': os.path.join('common', 'main', '%(locale)s.xml'),
     122        'pattern': "/ldml/dates/calendars/calendar[@type='gregorian']/dateFormats/dateFormatLength[@type='medium']/dateFormat/pattern",
     123        'conversion': convert_time,
     124    },
     125    {
     126        'name': 'SHORT_DATETIME_FORMAT',
     127        'file': os.path.join('common', 'main', '%(locale)s.xml'),
     128        'pattern': "/ldml/dates/calendars/calendar[@type='gregorian']/dateTimeFormats/dateTimeFormatLength[@type='short']/dateTimeFormat/pattern",
     129        'conversion': datetime,
     130    },
     131    {'name': 'FIRST_DAY_OF_WEEK'},
     132    {'name': 'DATE_INPUT_FORMATS'},
     133    {'name': 'TIME_INPUT_FORMATS'},
     134    {'name': 'DATETIME_INPUT_FORMATS'},
     135    {
     136        'name': 'DECIMAL_SEPARATOR',
     137        'file': os.path.join('common', 'main', '%(locale)s.xml'),
     138        'pattern': "/ldml/numbers/symbols/decimal",
     139        'conversion': quote,
     140    },
     141    {
     142        'name': 'THOUSAND_SEPARATOR',
     143        'file': os.path.join('common', 'main', '%(locale)s.xml'),
     144        'pattern': "/ldml/numbers/symbols/group",
     145        'conversion': quote,
     146    },
     147    {'name': 'NUMBER_GROUPING'},
     148]
     149"""
     150"""
     151
     152def get_locales(django_locale_dir, locale=None):
     153    if locale:
     154        yield locale
     155    else:
     156        locale_re = re.compile('[a-z]{2}(_[A-Z]{2})?')
     157        for locale in os.listdir(django_locale_dir):
     158            if locale_re.match(locale):
     159                yield locale
     160
     161def import_cldr(cldr_dir, locale=None, overwrite=False):
     162    """
     163    For every locale defined in Django, get from the CLDR locale file all
     164    settings defined in output_structure, and write the result to the
     165    locale directories on Django.
     166    """
     167    if not os.path.isdir(cldr_dir):
     168        raise Exception, "Specified CLDR directory '%s' does not exist" % cldr_dir
     169
     170    import django
     171    django_locale_dir = os.path.join(os.path.dirname(django.__file__), 'conf', 'locale')
     172
     173    for locale in get_locales(django_locale_dir, locale):
     174        output_filename = os.path.join(django_locale_dir, locale, FORMATS_FILE_NAME)
     175        if os.path.isfile(output_filename) and not overwrite:
     176            print "'%s' locale already exists. Skipping" % locale
     177        else:
     178            result = {}
     179            output_file = open(output_filename, 'w')
     180            output_file.write(FORMATS_FILE_HEADER)
     181            for format in FORMATS_MAP:
     182                if 'file' in format:
     183                    cldr_file = os.path.join(cldr_dir, format['file'] % dict(locale=locale))
     184                    tree = etree.parse(cldr_file) # TODO: error control
     185                    try:
     186                        original_value = tree.xpath(format['pattern'])
     187                    except IndexError:
     188                        output_file.write('# %s = \n' % (format['name']))
     189                    else:
     190                        value = format['conversion'](original_value, format['name'], locale, result)
     191                        if value:
     192                            output_file.write('%s = %s\n' % (format['name'], value.encode('utf8')))
     193                            result[format['name']] = value
     194                        else:
     195                            output_file.write('# %s = \n' % (format['name']))
     196                else:
     197                    output_file.write('# %s = \n' % (format['name']))
     198            output_file.close()
     199
     200            init_filename = os.path.join(django_locale_dir, locale, '__init__.py')
     201            open(init_filename, 'a').close()
     202
     203class Command(LabelCommand):
     204    option_list = LabelCommand.option_list + (
     205        make_option('--locale', '-l', dest='locale',
     206            help='The locale to process. Default is to process all.'),
     207    ) + (
     208        make_option('--overwite', '-o', action='store_true', dest='overwrite',
     209            help='Wheter to overwrite format definitions of locales that already have one.'),
     210    )
     211    help = 'Creates format definition files for locales, importing data from the CLDR.'
     212    args = '[cldrpath]'
     213    label = 'CLDR path'
     214    requires_model_validation = False
     215    can_import_settings = False
     216
     217    def handle_label(self, cldrpath, **options):
     218        locale = options.get('locale')
     219        overwrite = options.get('overwrite')
     220        import_cldr(cldrpath, locale, overwrite)
     221
  • django/views/i18n.py

     
    33from django.utils import importlib
    44from django.utils.translation import check_for_language, activate, to_locale, get_language
    55from django.utils.text import javascript_quote
     6from django.utils.formats import project_formats_module, django_formats_module
    67import os
    78import gettext as gettext_module
    89
     
    3233                response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code)
    3334    return response
    3435
     36def get_formats():
     37    """
     38    Returns an iterator over all formats in formats file
     39    """
     40    FORMAT_SETTINGS = ('DATE_FORMAT', 'DATETIME_FORMAT', 'TIME_FORMAT',
     41        'YEAR_MONTH_FORMAT', 'MONTH_DAY_FORMAT', 'SHORT_DATE_FORMAT',
     42        'SHORT_DATETIME_FORMAT', 'FIRST_DAY_OF_WEEK', 'DECIMAL_SEPARATOR',
     43        'THOUSAND_SEPARATOR', 'NUMBER_GROUPING')
     44
     45    result = {}
     46    for module in (settings, django_formats_module(), project_formats_module()):
     47        if module:
     48            for attr in FORMAT_SETTINGS:
     49                try:
     50                    result[attr] = getattr(module, attr)
     51                except AttributeError:
     52                    pass
     53    return result
     54   
    3555NullSource = """
    3656/* gettext identity library */
    3757
     
    185205        else:
    186206            raise TypeError, k
    187207    csrc.sort()
    188     for k,v in pdict.items():
     208    for k, v in pdict.items():
    189209        src.append("catalog['%s'] = [%s];\n" % (javascript_quote(k), ','.join(["''"]*(v+1))))
     210    for k, v in get_formats().items():
     211        src.append("catalog['%s'] = '%s';\n" % (javascript_quote(k), javascript_quote(unicode(v))))
    190212    src.extend(csrc)
    191213    src.append(LibFoot)
    192214    src.append(InterPolate)
    193215    src = ''.join(src)
    194216    return http.HttpResponse(src, 'text/javascript')
     217
  • django/utils/numberformat.py

     
     1from django.conf import settings
     2
     3def format(number, decimal_sep, decimal_pos, grouping=0, thousand_sep=''):
     4    """
     5    Gets a number (as a number or string), and returns it as a string,
     6    using formats definied as arguments:
     7     * decimal_sep: Decimal separator symbol (for example ".")
     8     * decimal_pos: Number of decimal positions
     9     * grouping: Number of digits in every group limited by thousand separator
     10     * thousand_sep: Thousand separator symbol (for example ",")
     11    """
     12    # sign
     13    if number < 0:
     14        sign = '-'
     15    else:
     16        sign = ''
     17    # decimal part
     18    str_number = unicode(number)
     19    if str_number[0] == '-':
     20        str_number = str_number[1:]
     21    if '.' in str_number:
     22        int_part, dec_part = str_number.split('.')
     23        if decimal_pos:
     24            dec_part = dec_part[:decimal_pos]
     25    else:
     26        int_part, dec_part = str_number, ''
     27    if decimal_pos:
     28        dec_part = dec_part + ('0' * (decimal_pos - len(dec_part)))
     29    if dec_part: dec_part = decimal_sep + dec_part
     30    # grouping
     31    if settings.USE_THOUSAND_SEPARATOR and grouping:
     32        int_part_gd = ''
     33        for cnt, digit in enumerate(int_part[::-1]):
     34            if cnt and not cnt % grouping:
     35                int_part_gd += thousand_sep
     36            int_part_gd += digit
     37        int_part = int_part_gd[::-1]
     38
     39    return sign + int_part + dec_part
     40
  • django/utils/translation/trans_real.py

     
    266266    translation object to use. If no current translation is activated, the
    267267    message will be run through the default translation object.
    268268    """
     269    eol_message = message.replace('\r\n', '\n').replace('\r', '\n')
    269270    global _default, _active
    270271    t = _active.get(currentThread(), None)
    271272    if t is not None:
    272         result = getattr(t, translation_function)(message)
     273        result = getattr(t, translation_function)(eol_message)
    273274    else:
    274275        if _default is None:
    275276            from django.conf import settings
    276277            _default = translation(settings.LANGUAGE_CODE)
    277         result = getattr(_default, translation_function)(message)
     278        result = getattr(_default, translation_function)(eol_message)
    278279    if isinstance(message, SafeData):
    279280        return mark_safe(result)
    280281    return result
     
    389390
    390391    return settings.LANGUAGE_CODE
    391392
    392 def get_date_formats():
    393     """
    394     Checks whether translation files provide a translation for some technical
    395     message ID to store date and time formats. If it doesn't contain one, the
    396     formats provided in the settings will be used.
    397     """
    398     from django.conf import settings
    399     date_format = ugettext('DATE_FORMAT')
    400     datetime_format = ugettext('DATETIME_FORMAT')
    401     time_format = ugettext('TIME_FORMAT')
    402     if date_format == 'DATE_FORMAT':
    403         date_format = settings.DATE_FORMAT
    404     if datetime_format == 'DATETIME_FORMAT':
    405         datetime_format = settings.DATETIME_FORMAT
    406     if time_format == 'TIME_FORMAT':
    407         time_format = settings.TIME_FORMAT
    408     return date_format, datetime_format, time_format
    409 
    410 def get_partial_date_formats():
    411     """
    412     Checks whether translation files provide a translation for some technical
    413     message ID to store partial date formats. If it doesn't contain one, the
    414     formats provided in the settings will be used.
    415     """
    416     from django.conf import settings
    417     year_month_format = ugettext('YEAR_MONTH_FORMAT')
    418     month_day_format = ugettext('MONTH_DAY_FORMAT')
    419     if year_month_format == 'YEAR_MONTH_FORMAT':
    420         year_month_format = settings.YEAR_MONTH_FORMAT
    421     if month_day_format == 'MONTH_DAY_FORMAT':
    422         month_day_format = settings.MONTH_DAY_FORMAT
    423     return year_month_format, month_day_format
    424 
    425393dot_re = re.compile(r'\S')
    426394def blankout(src, char):
    427395    """
     
    537505        result.append((lang, priority))
    538506    result.sort(lambda x, y: -cmp(x[1], y[1]))
    539507    return result
     508
     509# get_date_formats and get_partial_date_formats aren't used anymore from django
     510# itself, and are kept for backward compatibility.
     511# Note that it's also important to keep format names maked for translation, so
     512# for compatibility we still want to have formats on translation catalogs. That
     513# makes template code like {{ my_date|date:_('DATE_FORMAT') }} go on working
     514def get_date_formats():
     515    """
     516    Checks whether translation files provide a translation for some technical
     517    message ID to store date and time formats. If it doesn't contain one, the
     518    formats provided in the settings will be used.
     519    """
     520    from django.conf import settings
     521    date_format = ugettext('DATE_FORMAT')
     522    datetime_format = ugettext('DATETIME_FORMAT')
     523    time_format = ugettext('TIME_FORMAT')
     524    if date_format == 'DATE_FORMAT':
     525        date_format = settings.DATE_FORMAT
     526    if datetime_format == 'DATETIME_FORMAT':
     527        datetime_format = settings.DATETIME_FORMAT
     528    if time_format == 'TIME_FORMAT':
     529        time_format = settings.TIME_FORMAT
     530    return date_format, datetime_format, time_format
     531
     532def get_partial_date_formats():
     533    """
     534    Checks whether translation files provide a translation for some technical
     535    message ID to store partial date formats. If it doesn't contain one, the
     536    formats provided in the settings will be used.
     537    """
     538    from django.conf import settings
     539    year_month_format = ugettext('YEAR_MONTH_FORMAT')
     540    month_day_format = ugettext('MONTH_DAY_FORMAT')
     541    if year_month_format == 'YEAR_MONTH_FORMAT':
     542        year_month_format = settings.YEAR_MONTH_FORMAT
     543    if month_day_format == 'MONTH_DAY_FORMAT':
     544        month_day_format = settings.MONTH_DAY_FORMAT
     545    return year_month_format, month_day_format
     546
  • django/utils/translation/trans_null.py

     
    1818deactivate = deactivate_all = lambda: None
    1919get_language = lambda: settings.LANGUAGE_CODE
    2020get_language_bidi = lambda: settings.LANGUAGE_CODE in settings.LANGUAGES_BIDI
    21 get_date_formats = lambda: (settings.DATE_FORMAT, settings.DATETIME_FORMAT, settings.TIME_FORMAT)
    22 get_partial_date_formats = lambda: (settings.YEAR_MONTH_FORMAT, settings.MONTH_DAY_FORMAT)
    2321check_for_language = lambda x: True
    2422
     23# date formats shouldn't be used using gettext anymore. This
     24# is kept for backward compatibility
    2525TECHNICAL_ID_MAP = {
    2626    "DATE_WITH_TIME_FULL": settings.DATETIME_FORMAT,
    2727    "DATE_FORMAT": settings.DATE_FORMAT,
     
    5151
    5252def get_language_from_request(request):
    5353    return settings.LANGUAGE_CODE
     54
     55# get_date_formats and get_partial_date_formats aren't used anymore from django
     56# itself, and are kept for backward compatibility.
     57get_date_formats = lambda: (settings.DATE_FORMAT, settings.DATETIME_FORMAT, settings.TIME_FORMAT)
     58get_partial_date_formats = lambda: (settings.YEAR_MONTH_FORMAT, settings.MONTH_DAY_FORMAT)
  • django/utils/formats.py

     
     1import decimal
     2import datetime
     3
     4from django.conf import settings
     5from django.utils.translation import get_language
     6from django.utils.importlib import import_module
     7from django.utils import dateformat
     8from django.utils import numberformat
     9
     10def project_formats_module():
     11    """
     12    Returns the formats module for the current locale, defined
     13    on the project
     14    """
     15    if settings.FORMAT_MODULE_PATH:
     16        try:
     17            return import_module('.formats', '%s.%s' % (settings.FORMAT_MODULE_PATH, get_language()))
     18        except ImportError:
     19            pass
     20    return None
     21
     22def django_formats_module():
     23    """
     24    Returns the formats module for the current locale, defined
     25    on Django
     26    """
     27    try:
     28        return import_module('.formats', 'django.conf.locale.%s' % get_language())
     29    except ImportError:
     30        return None
     31
     32def getformat(format_type):
     33    """
     34    For a specific format type, returns the format for the
     35    current language (locale) defaulting to the format on settings.
     36    format_type is the name of the format, for example 'DATE_FORMAT'
     37    """
     38    if settings.USE_I18N and settings.USE_FORMAT_I18N:
     39        for module in (project_formats_module(), django_formats_module()):
     40            if module:
     41                try:
     42                    return getattr(module, format_type)
     43                except AttributeError:
     44                    pass
     45    return getattr(settings, format_type)
     46
     47def date_format(value, format=None):
     48    """
     49    Formats a datetime.date or datetime.datetime object using a
     50    localizable format
     51    """
     52    return dateformat.format(value, getformat(format or 'DATE_FORMAT'))
     53
     54def number_format(value, decimal_pos=None):
     55    """
     56    Formats a numeric value using localization settings
     57    """
     58    return numberformat.format(
     59        value,
     60        getformat('DECIMAL_SEPARATOR'),
     61        decimal_pos,
     62        getformat('NUMBER_GROUPING'),
     63        getformat('THOUSAND_SEPARATOR'),
     64    )
     65
     66def localize(value, is_input=False):
     67    """
     68    Checks value, and if it has a localizable type (date,
     69    number...) it returns the value as a string using
     70    current locale format
     71    """
     72    if settings.USE_I18N and settings.USE_FORMAT_I18N:
     73        if isinstance(value, decimal.Decimal):
     74            return number_format(value)
     75        elif isinstance(value, float):
     76            return number_format(value)
     77        elif isinstance(value, int):
     78            return number_format(value)
     79        elif isinstance(value, datetime.datetime):
     80            if not is_input:
     81                return date_format(value, 'DATETIME_FORMAT')
     82            else:
     83                return value.strftime(getformat('DATETIME_INPUT_FORMATS')[0])
     84        elif isinstance(value, datetime.date):
     85            if not is_input:
     86                return date_format(value)
     87            else:
     88                return value.strftime(getformat('DATE_INPUT_FORMATS')[0])
     89        elif isinstance(value, datetime.time):
     90            if not is_input:
     91                return date_format(value, 'TIME_FORMAT')
     92            else:
     93                return value.strftime(getformat('TIME_INPUT_FORMATS')[0])
     94    return value
     95
  • django/contrib/admin/media/js/calendar.js

     
    2525var CalendarNamespace = {
    2626    monthsOfYear: gettext('January February March April May June July August September October November December').split(' '),
    2727    daysOfWeek: gettext('S M T W T F S').split(' '),
     28    firstDayOfWeek: parseInt(gettext('FIRST_DAY_OF_WEEK')),
    2829    isLeapYear: function(year) {
    2930        return (((year % 4)==0) && ((year % 100)!=0) || ((year % 400)==0));
    3031    },
     
    5657        // Draw days-of-week header
    5758        var tableRow = quickElement('tr', tableBody);
    5859        for (var i = 0; i < 7; i++) {
    59             quickElement('th', tableRow, CalendarNamespace.daysOfWeek[i]);
     60            quickElement('th', tableRow, CalendarNamespace.daysOfWeek[(i + CalendarNamespace.firstDayOfWeek) % 7]);
    6061        }
    6162
    62         var startingPos = new Date(year, month-1, 1).getDay();
     63        var startingPos = new Date(year, month-1, 1 - CalendarNamespace.firstDayOfWeek).getDay();
    6364        var days = CalendarNamespace.getDaysInMonth(month, year);
    6465
    6566        // Draw blanks before first of month
  • django/contrib/admin/templatetags/admin_list.py

     
    33from django.contrib.admin.views.main import ORDER_VAR, ORDER_TYPE_VAR, PAGE_VAR, SEARCH_VAR
    44from django.core.exceptions import ObjectDoesNotExist
    55from django.db import models
    6 from django.utils import dateformat
     6from django.utils import formats
    77from django.utils.html import escape, conditional_escape
    88from django.utils.text import capfirst
    99from django.utils.safestring import mark_safe
    10 from django.utils.translation import get_date_formats, get_partial_date_formats, ugettext as _
     10from django.utils.translation import ugettext as _
    1111from django.utils.encoding import smart_unicode, smart_str, force_unicode
    1212from django.template import Library
    1313import datetime
     
    184184            # Dates and times are special: They're formatted in a certain way.
    185185            elif isinstance(f, models.DateField) or isinstance(f, models.TimeField):
    186186                if field_val:
    187                     (date_format, datetime_format, time_format) = get_date_formats()
    188                     if isinstance(f, models.DateTimeField):
    189                         result_repr = capfirst(dateformat.format(field_val, datetime_format))
    190                     elif isinstance(f, models.TimeField):
    191                         result_repr = capfirst(dateformat.time_format(field_val, time_format))
    192                     else:
    193                         result_repr = capfirst(dateformat.format(field_val, date_format))
     187                    result_repr = formats.localize(field_val)
    194188                else:
    195189                    result_repr = EMPTY_CHANGELIST_VALUE
     190            elif isinstance(f, models.DecimalField):
     191                if field_val:
     192                    result_repr = formats.number_format(field_val, f.decimal_places)
     193                else:
     194                    result_repr = EMPTY_CHANGELIST_VALUE
    196195                row_class = ' class="nowrap"'
     196            elif isinstance(f, models.FloatField):
     197                if field_val:
     198                    result_repr = formats.number_format(field_val)
     199                else:
     200                    result_repr = EMPTY_CHANGELIST_VALUE
     201                row_class = ' class="nowrap"'
    197202            # Booleans are special: We use images.
    198203            elif isinstance(f, models.BooleanField) or isinstance(f, models.NullBooleanField):
    199204                result_repr = _boolean_icon(field_val)
    200             # DecimalFields are special: Zero-pad the decimals.
    201             elif isinstance(f, models.DecimalField):
    202                 if field_val is not None:
    203                     result_repr = ('%%.%sf' % f.decimal_places) % field_val
    204                 else:
    205                     result_repr = EMPTY_CHANGELIST_VALUE
    206205            # Fields with choices are special: Use the representation
    207206            # of the choice.
    208207            elif f.flatchoices:
     
    263262        year_lookup = cl.params.get(year_field)
    264263        month_lookup = cl.params.get(month_field)
    265264        day_lookup = cl.params.get(day_field)
    266         year_month_format, month_day_format = get_partial_date_formats()
    267265
    268266        link = lambda d: mark_safe(cl.get_query_string(d, [field_generic]))
    269267
     
    273271                'show': True,
    274272                'back': {
    275273                    'link': link({year_field: year_lookup, month_field: month_lookup}),
    276                     'title': dateformat.format(day, year_month_format)
     274                    'title': capfirst(formats.date_format(day, 'YEAR_MONTH_FORMAT'))
    277275                },
    278                 'choices': [{'title': dateformat.format(day, month_day_format)}]
     276                'choices': [{'title': capfirst(formats.date_format(day, 'MONTH_DAY_FORMAT'))}]
    279277            }
    280278        elif year_lookup and month_lookup:
    281279            days = cl.query_set.filter(**{year_field: year_lookup, month_field: month_lookup}).dates(field_name, 'day')
     
    287285                },
    288286                'choices': [{
    289287                    'link': link({year_field: year_lookup, month_field: month_lookup, day_field: day.day}),
    290                     'title': dateformat.format(day, month_day_format)
     288                    'title': capfirst(formats.date_format(day, 'MONTH_DAY_FORMAT'))
    291289                } for day in days]
    292290            }
    293291        elif year_lookup:
     
    300298                },
    301299                'choices': [{
    302300                    'link': link({year_field: year_lookup, month_field: month.month}),
    303                     'title': dateformat.format(month, year_month_format)
     301                    'title': capfirst(formats.date_format(month, 'YEAR_MONTH_FORMAT'))
    304302                } for month in months]
    305303            }
    306304        else:
  • django/contrib/admin/templates/admin/object_history.html

     
    2727        <tbody>
    2828        {% for action in action_list %}
    2929        <tr>
    30             <th scope="row">{{ action.action_time|date:_("DATETIME_FORMAT") }}</th>
     30            <th scope="row">{{ action.action_time|date }}</th>
    3131            <td>{{ action.user.username }}{% if action.user.get_full_name %} ({{ action.user.get_full_name }}){% endif %}</td>
    3232            <td>{{ action.change_message }}</td>
    3333        </tr>
  • django/contrib/databrowse/datastructures.py

     
    44"""
    55
    66from django.db import models
    7 from django.utils import dateformat
     7from django.utils import formats
    88from django.utils.text import capfirst
    9 from django.utils.translation import get_date_formats
    109from django.utils.encoding import smart_unicode, smart_str, iri_to_uri
    1110from django.utils.safestring import mark_safe
    1211from django.db.models.query import QuerySet
     
    156155            objs = dict(self.field.choices).get(self.raw_value, EMPTY_VALUE)
    157156        elif isinstance(self.field, models.DateField) or isinstance(self.field, models.TimeField):
    158157            if self.raw_value:
    159                 date_format, datetime_format, time_format = get_date_formats()
    160158                if isinstance(self.field, models.DateTimeField):
    161                     objs = capfirst(dateformat.format(self.raw_value, datetime_format))
     159                    objs = capfirst(formats.date_format(self.raw_value, 'DATETIME_FORMAT'))
    162160                elif isinstance(self.field, models.TimeField):
    163                     objs = capfirst(dateformat.time_format(self.raw_value, time_format))
     161                    objs = capfirst(formats.date_format(self.raw_value, 'TIME_FORMAT'))
    164162                else:
    165                     objs = capfirst(dateformat.format(self.raw_value, date_format))
     163                    objs = capfirst(formats.date_format(self.raw_value, 'DATE_FORMAT'))
    166164            else:
    167165                objs = EMPTY_VALUE
    168166        elif isinstance(self.field, models.BooleanField) or isinstance(self.field, models.NullBooleanField):
  • django/template/defaultfilters.py

     
    1818from django.utils.translation import ugettext, ungettext
    1919from django.utils.encoding import force_unicode, iri_to_uri
    2020from django.utils.safestring import mark_safe, SafeData
     21from django.utils.formats import date_format, number_format
    2122
    2223register = Library()
    2324
     
    166167        return input_val
    167168
    168169    if not m and p < 0:
    169         return mark_safe(u'%d' % (int(d)))
     170        return mark_safe(number_format(u'%d' % (int(d)), 0))
    170171
    171172    if p == 0:
    172173        exp = Decimal(1)
    173174    else:
    174175        exp = Decimal('1.0') / (Decimal(10) ** abs(p))
    175176    try:
    176         return mark_safe(u'%s' % str(d.quantize(exp, ROUND_HALF_UP)))
     177        return mark_safe(number_format(u'%s' % str(d.quantize(exp, ROUND_HALF_UP)), abs(p)))
    177178    except InvalidOperation:
    178179        return input_val
    179180floatformat.is_safe = True
     
    684685    if arg is None:
    685686        arg = settings.DATE_FORMAT
    686687    try:
    687         return format(value, arg)
     688        return date_format(value, arg)
    688689    except AttributeError:
    689         return ''
     690        try:
     691            return format(value, arg)
     692        except AttributeError:
     693            return ''
    690694date.is_safe = False
    691695
    692696def time(value, arg=None):
     
    697701    if arg is None:
    698702        arg = settings.TIME_FORMAT
    699703    try:
    700         return time_format(value, arg)
     704        return date_format(value, arg)
    701705    except AttributeError:
    702         return ''
     706        try:
     707            return time_format(value, arg)
     708        except AttributeError:
     709            return ''
    703710time.is_safe = False
    704711
    705712def timesince(value, arg=None):
  • django/template/__init__.py

     
    6060from django.utils.encoding import smart_unicode, force_unicode, smart_str
    6161from django.utils.translation import ugettext as _
    6262from django.utils.safestring import SafeData, EscapeData, mark_safe, mark_for_escaping
     63from django.utils.formats import localize
    6364from django.utils.html import escape
    6465
    6566__all__ = ('Template', 'Context', 'RequestContext', 'compile_string')
     
    808809    means escaping, if required, and conversion to a unicode object. If value
    809810    is a string, it is expected to have already been translated.
    810811    """
     812    value = localize(value)
    811813    value = force_unicode(value)
    812814    if (context.autoescape and not isinstance(value, SafeData)) or isinstance(value, EscapeData):
    813815        return escape(value)
  • django/template/debug.py

     
    22from django.utils.encoding import force_unicode
    33from django.utils.html import escape
    44from django.utils.safestring import SafeData, EscapeData
     5from django.utils.formats import localize
    56
    67class DebugLexer(Lexer):
    78    def __init__(self, template_string, origin):
     
    8485class DebugVariableNode(VariableNode):
    8586    def render(self, context):
    8687        try:
    87             output = force_unicode(self.filter_expression.resolve(context))
     88            output = self.filter_expression.resolve(context)
     89            output = localize(output)
     90            output = force_unicode(output)
    8891        except TemplateSyntaxError, e:
    8992            if not hasattr(e, 'source'):
    9093                e.source = self.source
  • tests/regressiontests/i18n/tests.py

     
    6464'as'
    6565>>> print s
    6666Password
     67
     68Translations on files with mac or dos end of lines will be converted
     69to unix eof in .po catalogs, and they have to match when retrieved
     70
     71>>> from django.utils.translation.trans_real import translation
     72>>> ca_translation = translation('ca')
     73>>> ca_translation._catalog[u'Mac\nEOF\n'] = u'Catalan Mac\nEOF\n'
     74>>> ca_translation._catalog[u'Win\nEOF\n'] = u'Catalan Win\nEOF\n'
     75>>> activate('ca')
     76>>> ugettext(u'Mac\rEOF\r')
     77u'Catalan Mac\nEOF\n'
     78>>> ugettext(u'Win\r\nEOF\r\n')
     79u'Catalan Win\nEOF\n'
     80>>> deactivate()
     81
     82Localization of dates and numbers
     83
     84>>> import datetime
     85>>> import decimal
     86>>> from django.conf import settings
     87>>> from django.utils.formats import getformat, date_format, number_format, localize
     88>>> from django.utils.numberformat import format
     89>>> from django import template
     90>>> from django import forms
     91>>> from django.forms.extras import SelectDateWidget
     92
     93>>> old_use_i18n = settings.USE_I18N
     94>>> old_use_format_i18n = settings.USE_FORMAT_I18N
     95>>> old_use_thousand_separator = settings.USE_THOUSAND_SEPARATOR
     96
     97>>> n = decimal.Decimal('66666.666')
     98>>> f = 99999.999
     99>>> d = datetime.date(2009, 12, 31)
     100>>> dt = datetime.datetime(2009, 12, 31, 20, 50)
     101>>> ctxt = template.Context({'n': n, 'd': d, 'dt': dt, 'f': f})
     102>>> class I18nForm(forms.Form):
     103...     decimal_field = forms.DecimalField()
     104...     float_field = forms.FloatField()
     105...     date_field = forms.DateField()
     106...     datetime_field = forms.DateTimeField()
     107...     time_field = forms.TimeField()
     108>>> class SelectDateForm(forms.Form):
     109...     date_field = forms.DateField(widget=SelectDateWidget)
     110
     111Locale independent
     112
     113>>> settings.USE_FORMAT_I18N = True
     114>>> settings.USE_THOUSAND_SEPARATOR = False
     115>>> format(n, decimal_sep='.', decimal_pos=2, grouping=3, thousand_sep=',')
     116u'66666.66'
     117>>> format(n, decimal_sep='A', decimal_pos=1, grouping=1, thousand_sep='B')
     118u'66666A6'
     119>>> settings.USE_THOUSAND_SEPARATOR = True
     120>>> format(n, decimal_sep='.', decimal_pos=2, grouping=3, thousand_sep=',')
     121u'66,666.66'
     122>>> format(n, decimal_sep='A', decimal_pos=1, grouping=1, thousand_sep='B')
     123u'6B6B6B6B6A6'
     124
     125Catalan locale with format i18n disabled
     126translations will be used, but not formats
     127
     128>>> settings.USE_FORMAT_I18N = False
     129>>> activate('ca')
     130>>> getformat('DATE_FORMAT')
     131'N j, Y'
     132>>> getformat('FIRST_DAY_OF_WEEK')
     1330
     134>>> getformat('DECIMAL_SEPARATOR')
     135'.'
     136>>> date_format(d)
     137u'des. 31, 2009'
     138>>> date_format(d, 'YEAR_MONTH_FORMAT')
     139u'desembre 2009'
     140>>> date_format(dt, 'SHORT_DATETIME_FORMAT')
     141u'12/31/2009 8:50 p.m.'
     142>>> localize('No localizable')
     143'No localizable'
     144>>> localize(n)
     145Decimal('66666.666')
     146>>> localize(f)
     14799999.999
     148>>> localize(d)
     149datetime.date(2009, 12, 31)
     150>>> localize(dt)
     151datetime.datetime(2009, 12, 31, 20, 50)
     152>>> template.Template('{{ n }}').render(ctxt)
     153u'66666.666'
     154>>> template.Template('{{ f }}').render(ctxt)
     155u'99999.999'
     156>>> template.Template('{{ d }}').render(ctxt)
     157u'2009-12-31'
     158>>> template.Template('{{ dt }}').render(ctxt)
     159u'2009-12-31 20:50:00'
     160>>> template.Template('{{ n|floatformat:2 }}').render(ctxt)
     161u'66666.67'
     162>>> template.Template('{{ f|floatformat }}').render(ctxt)
     163u'100000.0'
     164>>> template.Template('{{ d|date:"SHORT_DATE_FORMAT" }}').render(ctxt)
     165u'12/31/2009'
     166>>> template.Template('{{ dt|date:"SHORT_DATETIME_FORMAT" }}').render(ctxt)
     167u'12/31/2009 8:50 p.m.'
     168>>> form = I18nForm({'decimal_field': u'66666,666', 'float_field': u'99999,999', 'date_field': u'31/12/2009', 'datetime_field': u'31/12/2009 20:50', 'time_field': u'20:50'})
     169>>> form.is_valid()
     170False
     171>>> form.errors['float_field']
     172[u'Introdu\xefu un n\xfamero.']
     173>>> form.errors['decimal_field']
     174[u'Introdu\xefu un n\xfamero.']
     175>>> form.errors['date_field']
     176[u'Introdu\xefu una data v\xe0lida.']
     177>>> form.errors['datetime_field']
     178[u'Introdu\xefu una data/hora v\xe0lides.']
     179>>> form2 = SelectDateForm({'date_field_month': u'12', 'date_field_day': u'31', 'date_field_year': u'2009'})
     180>>> form2.is_valid()
     181True
     182>>> form2.cleaned_data['date_field']
     183datetime.date(2009, 12, 31)
     184>>> SelectDateWidget().render('mydate', datetime.date(2009, 12, 31))
     185u'<select name="mydate_month" id="id_mydate_month">\n<option value="1">gener</option>\n<option value="2">febrer</option>\n<option value="3">mar\xe7</option>\n<option value="4">abril</option>\n<option value="5">maig</option>\n<option value="6">juny</option>\n<option value="7">juliol</option>\n<option value="8">agost</option>\n<option value="9">setembre</option>\n<option value="10">octubre</option>\n<option value="11">novembre</option>\n<option value="12" selected="selected">desembre</option>\n</select>\n<select name="mydate_day" id="id_mydate_day">\n<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31" selected="selected">31</option>\n</select>\n<select name="mydate_year" id="id_mydate_year">\n<option value="2009" selected="selected">2009</option>\n<option value="2010">2010</option>\n<option value="2011">2011</option>\n<option value="2012">2012</option>\n<option value="2013">2013</option>\n<option value="2014">2014</option>\n<option value="2015">2015</option>\n<option value="2016">2016</option>\n<option value="2017">2017</option>\n<option value="2018">2018</option>\n</select>'
     186
     187Catalan locale
     188
     189>>> settings.USE_FORMAT_I18N = True
     190>>> activate('ca')
     191>>> getformat('DATE_FORMAT')
     192'j \\de F \\de Y'
     193>>> getformat('FIRST_DAY_OF_WEEK')
     1941
     195>>> getformat('DECIMAL_SEPARATOR')
     196','
     197>>> date_format(d)
     198u'31 de desembre de 2009'
     199>>> date_format(d, 'YEAR_MONTH_FORMAT')
     200u'desembre del 2009'
     201>>> date_format(dt, 'SHORT_DATETIME_FORMAT')
     202u'31/12/2009 20:50'
     203>>> localize('No localizable')
     204'No localizable'
     205>>> settings.USE_THOUSAND_SEPARATOR = True
     206>>> localize(n)
     207u'66.666,666'
     208>>> localize(f)
     209u'99.999,999'
     210>>> settings.USE_THOUSAND_SEPARATOR = False
     211>>> localize(n)
     212u'66666,666'
     213>>> localize(f)
     214u'99999,999'
     215>>> localize(d)
     216u'31 de desembre de 2009'
     217>>> localize(dt)
     218u'31 de desembre de 2009 a les 20:50'
     219>>> settings.USE_THOUSAND_SEPARATOR = True
     220>>> template.Template('{{ n }}').render(ctxt)
     221u'66.666,666'
     222>>> template.Template('{{ f }}').render(ctxt)
     223u'99.999,999'
     224>>> settings.USE_THOUSAND_SEPARATOR = False
     225>>> template.Template('{{ n }}').render(ctxt)
     226u'66666,666'
     227>>> template.Template('{{ f }}').render(ctxt)
     228u'99999,999'
     229>>> template.Template('{{ d }}').render(ctxt)
     230u'31 de desembre de 2009'
     231>>> template.Template('{{ dt }}').render(ctxt)
     232u'31 de desembre de 2009 a les 20:50'
     233>>> template.Template('{{ n|floatformat:2 }}').render(ctxt)
     234u'66666,67'
     235>>> template.Template('{{ f|floatformat }}').render(ctxt)
     236u'100000,0'
     237>>> template.Template('{{ d|date:"SHORT_DATE_FORMAT" }}').render(ctxt)
     238u'31/12/2009'
     239>>> template.Template('{{ dt|date:"SHORT_DATETIME_FORMAT" }}').render(ctxt)
     240u'31/12/2009 20:50'
     241>>> form = I18nForm({'decimal_field': u'66666,666', 'float_field': u'99999,999', 'date_field': u'31/12/2009', 'datetime_field': u'31/12/2009 20:50', 'time_field': u'20:50'})
     242>>> form.is_valid()
     243True
     244>>> form.cleaned_data['decimal_field']
     245Decimal('66666.666')
     246>>> form.cleaned_data['float_field']
     24799999.999
     248>>> form.cleaned_data['date_field']
     249datetime.date(2009, 12, 31)
     250>>> form.cleaned_data['datetime_field']
     251datetime.datetime(2009, 12, 31, 20, 50)
     252>>> form.cleaned_data['time_field']
     253datetime.time(20, 50)
     254>>> form2 = SelectDateForm({'date_field_month': u'12', 'date_field_day': u'31', 'date_field_year': u'2009'})
     255>>> form2.is_valid()
     256True
     257>>> form2.cleaned_data['date_field']
     258datetime.date(2009, 12, 31)
     259>>> SelectDateWidget().render('mydate', datetime.date(2009, 12, 31))
     260u'<select name="mydate_day" id="id_mydate_day">\n<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31" selected="selected">31</option>\n</select>\n<select name="mydate_month" id="id_mydate_month">\n<option value="1">gener</option>\n<option value="2">febrer</option>\n<option value="3">mar\xe7</option>\n<option value="4">abril</option>\n<option value="5">maig</option>\n<option value="6">juny</option>\n<option value="7">juliol</option>\n<option value="8">agost</option>\n<option value="9">setembre</option>\n<option value="10">octubre</option>\n<option value="11">novembre</option>\n<option value="12" selected="selected">desembre</option>\n</select>\n<select name="mydate_year" id="id_mydate_year">\n<option value="2009" selected="selected">2009</option>\n<option value="2010">2010</option>\n<option value="2011">2011</option>\n<option value="2012">2012</option>\n<option value="2013">2013</option>\n<option value="2014">2014</option>\n<option value="2015">2015</option>\n<option value="2016">2016</option>\n<option value="2017">2017</option>\n<option value="2018">2018</option>\n</select>'
     261
     262English locale
     263
     264>>> settings.USE_FORMAT_I18N = True
     265>>> activate('en')
     266>>> getformat('DATE_FORMAT')
     267'N j, Y'
     268>>> getformat('FIRST_DAY_OF_WEEK')
     2690
     270>>> getformat('DECIMAL_SEPARATOR')
     271'.'
     272>>> date_format(d)
     273u'Dec. 31, 2009'
     274>>> date_format(d, 'YEAR_MONTH_FORMAT')
     275u'December 2009'
     276>>> date_format(dt, 'SHORT_DATETIME_FORMAT')
     277u'12/31/2009 8:50 p.m.'
     278>>> localize('No localizable')
     279'No localizable'
     280>>> settings.USE_THOUSAND_SEPARATOR = True
     281>>> localize(n)
     282u'66,666.666'
     283>>> localize(f)
     284u'99,999.999'
     285>>> settings.USE_THOUSAND_SEPARATOR = False
     286>>> localize(n)
     287u'66666.666'
     288>>> localize(f)
     289u'99999.999'
     290>>> localize(d)
     291u'Dec. 31, 2009'
     292>>> localize(dt)
     293u'Dec. 31, 2009, 8:50 p.m.'
     294>>> settings.USE_THOUSAND_SEPARATOR = True
     295>>> template.Template('{{ n }}').render(ctxt)
     296u'66,666.666'
     297>>> template.Template('{{ f }}').render(ctxt)
     298u'99,999.999'
     299>>> settings.USE_THOUSAND_SEPARATOR = False
     300>>> template.Template('{{ n }}').render(ctxt)
     301u'66666.666'
     302>>> template.Template('{{ f }}').render(ctxt)
     303u'99999.999'
     304>>> template.Template('{{ d }}').render(ctxt)
     305u'Dec. 31, 2009'
     306>>> template.Template('{{ dt }}').render(ctxt)
     307u'Dec. 31, 2009, 8:50 p.m.'
     308>>> template.Template('{{ n|floatformat:2 }}').render(ctxt)
     309u'66666.67'
     310>>> template.Template('{{ f|floatformat }}').render(ctxt)
     311u'100000.0'
     312>>> template.Template('{{ d|date:"SHORT_DATE_FORMAT" }}').render(ctxt)
     313u'12/31/2009'
     314>>> template.Template('{{ dt|date:"SHORT_DATETIME_FORMAT" }}').render(ctxt)
     315u'12/31/2009 8:50 p.m.'
     316>>> form = I18nForm({'decimal_field': u'66666.666', 'float_field': u'99999.999', 'date_field': u'12/31/2009', 'datetime_field': u'12/31/2009 20:50', 'time_field': u'20:50'})
     317>>> form.is_valid()
     318True
     319>>> form.cleaned_data['decimal_field']
     320Decimal('66666.666')
     321>>> form.cleaned_data['float_field']
     32299999.999
     323>>> form.cleaned_data['date_field']
     324datetime.date(2009, 12, 31)
     325>>> form.cleaned_data['datetime_field']
     326datetime.datetime(2009, 12, 31, 20, 50)
     327>>> form.cleaned_data['time_field']
     328datetime.time(20, 50)
     329>>> form2 = SelectDateForm({'date_field_month': u'12', 'date_field_day': u'31', 'date_field_year': u'2009'})
     330>>> form2.is_valid()
     331True
     332>>> form2.cleaned_data['date_field']
     333datetime.date(2009, 12, 31)
     334>>> SelectDateWidget().render('mydate', datetime.date(2009, 12, 31))
     335u'<select name="mydate_month" id="id_mydate_month">\n<option value="1">January</option>\n<option value="2">February</option>\n<option value="3">March</option>\n<option value="4">April</option>\n<option value="5">May</option>\n<option value="6">June</option>\n<option value="7">July</option>\n<option value="8">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12" selected="selected">December</option>\n</select>\n<select name="mydate_day" id="id_mydate_day">\n<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31" selected="selected">31</option>\n</select>\n<select name="mydate_year" id="id_mydate_year">\n<option value="2009" selected="selected">2009</option>\n<option value="2010">2010</option>\n<option value="2011">2011</option>\n<option value="2012">2012</option>\n<option value="2013">2013</option>\n<option value="2014">2014</option>\n<option value="2015">2015</option>\n<option value="2016">2016</option>\n<option value="2017">2017</option>\n<option value="2018">2018</option>\n</select>'
     336
     337Restore defaults
     338
     339>>> settings.USE_I18N = old_use_i18n
     340>>> settings.USE_FORMAT_I18N = old_use_format_i18n
     341>>> settings.USE_THOUSAND_SEPARATOR = old_use_thousand_separator
     342>>> deactivate()
     343
    67344"""
    68345
    69346__test__ = {
  • docs/topics/i18n.txt

     
    44Internationalization
    55====================
    66
    7 Django has full support for internationalization of text in code and templates.
    8 Here's how it works.
     7Django has full support for internationalization, including translation
     8capabilities of text in code and templates, and format localization for
     9dates and numbers. Here's how it works.
    910
    1011Overview
    1112========
    1213
    1314The goal of internationalization is to allow a single Web application to offer
    14 its content and functionality in multiple languages.
     15its content and functionality in multiple languages and locales.
    1516
    16 You, the Django developer, can accomplish this goal by adding a minimal amount
    17 of hooks to your Python code and templates. These hooks are called
    18 **translation strings**. They tell Django: "This text should be translated into
    19 the end user's language, if a translation for this text is available in that
    20 language."
     17For text translation, you, the Django developer, can accomplish this goal by
     18adding a minimal amount of hooks to your Python code and templates. These hooks
     19are called **translation strings**. They tell Django: "This text should be
     20translated into the end user's language, if a translation for this text is
     21available in that language."
    2122
    2223Django takes care of using these hooks to translate Web apps, on the fly,
    2324according to users' language preferences.
     
    2930    * It uses these hooks to translate Web apps for particular users according
    3031      to their language preferences.
    3132
     33For format localization, it's just necessary to set
     34:setting:`USE_FORMAT_I18N = True <USE_FORMAT_I18N>` in your settings file. If
     35:settings:`USE_FORMAT_I18N` is set to ``True``, then Django will display
     36numbers and dates in the format of the current locale. That includes field
     37representation on templates, and allowed input formats on the admin.
     38
    3239If you don't need internationalization in your app
    3340==================================================
    3441
     
    10741081translation utilities with a ``gettext`` package if the command ``xgettext
    10751082--version`` entered at a Windows command prompt causes a popup window saying
    10761083"xgettext.exe has generated errors and will be closed by Windows".
     1084
     1085Format localization
     1086===================
     1087
     1088Django's formatting system is disabled by default. To enable it, it's necessay
     1089to set :setting:`USE_FORMAT_I18N = True <USE_FORMAT_I18N>` in your settings
     1090file.  Note that :setting:`USE_FORMAT_I18N` requires `USE_I18N` to be ``True``.
     1091
     1092When using Django's formatting system, dates and numbers on templates will be
     1093displayed using the format specified for the current locale. That means, two
     1094users accessing the same content, but in different language, will see date and
     1095number fields formatted in different ways, depending on the format for their
     1096current locale.
     1097
     1098Django will also use localized formats when parsing data in forms. That means
     1099Django uses different formats for different locales when guessing the format
     1100used by the user when inputting data on forms. Note that Django uses different
     1101formats for displaying data, and for parsing it.
     1102
     1103Creating custom format files
     1104----------------------------
     1105
     1106Django provides format definitions for many locales, but sometimes you could
     1107want to create your own ones, because a format files doesn't exist for your
     1108locale, or because you want to overwrite some of the values.
     1109
     1110To use custom formats, first thing to do, is to specify the path where you'll
     1111place format files. To do that, just set :setting:`FORMAT_MODULE_PATH` setting
     1112to the the path (in the format ``'foo.bar.baz``) where format files will
     1113exists.
     1114
     1115Files are not placed directly in this directory, but in a directory named as
     1116the locale. File must be named ``formats.py``.
     1117
     1118For customazing English formats, a structure like this would be needed::
     1119
     1120    mysite/
     1121        formats/
     1122            __init__.py
     1123            en/
     1124                __init__.py
     1125                formats.py
     1126
     1127where :file:`formats.py` contains custom format definitions. For example::
     1128
     1129    THOUSAND_SEPARATOR = ' '
     1130
     1131to use a space as thousand separator, instead of the default for English,
     1132comma.
     1133
  • docs/ref/settings.txt

     
    243243
    244244Default: ``'N j, Y'`` (e.g. ``Feb. 4, 2003``)
    245245
    246 The default formatting to use for date fields on Django admin change-list
    247 pages -- and, possibly, by other parts of the system. See
    248 :ttag:`allowed date format strings <now>`.
     246The default formatting to use for date fields in any part of the system.
     247Note that if ``USE_FORMAT_I18N`` is set to ``True``, then locale format will
     248be applied. See :ttag:`allowed date format strings <now>`.
    249249
    250 See also ``DATETIME_FORMAT``, ``TIME_FORMAT``, ``YEAR_MONTH_FORMAT``
    251 and ``MONTH_DAY_FORMAT``.
     250See also ``DATETIME_FORMAT``, ``TIME_FORMAT`` and ``SHORT_DATE_FORMAT``.
    252251
     252.. setting:: DATE_INPUT_FORMATS
     253
     254DATE_INPUT_FORMATS
     255------------------
     256
     257Default::
     258
     259    ('%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', '%b %d %Y',
     260    '%b %d, %Y', '%d %b %Y', '%d %b, %Y', '%B %d %Y',
     261    '%B %d, %Y', '%d %B %Y', '%d %B, %Y')
     262
     263A tuple of formats that will be accepted when inputting data on a date
     264field. Formats will be tried in order, using the first valid.
     265Note that these format strings are specified in Python's datetime_ module
     266syntax, that is different from the one used by Django for formatting dates
     267to be displayed.
     268
     269See also ``DATETIME_INPUT_FORMATS`` and ``TIME_INPUT_FORMATS``.
     270
     271.. _datetime: http://docs.python.org/library/datetime.html#strftime-behavior
     272
    253273.. setting:: DATETIME_FORMAT
    254274
    255275DATETIME_FORMAT
     
    257277
    258278Default: ``'N j, Y, P'`` (e.g. ``Feb. 4, 2003, 4 p.m.``)
    259279
    260 The default formatting to use for datetime fields on Django admin change-list
    261 pages -- and, possibly, by other parts of the system. See
    262 :ttag:`allowed date format strings <now>`.
     280The default formatting to use for datetime fields in any part of the system.
     281Note that if ``USE_FORMAT_I18N`` is set to ``True``, then locale format will
     282be applied. See :ttag:`allowed date format strings <now>`.
    263283
    264 See also ``DATE_FORMAT``, ``DATETIME_FORMAT``, ``TIME_FORMAT``,
    265 ``YEAR_MONTH_FORMAT`` and ``MONTH_DAY_FORMAT``.
     284See also ``DATE_FORMAT``, ``TIME_FORMAT`` and ``SHORT_DATETIME_FORMAT``.
    266285
     286.. setting:: DATETIME_INPUT_FORMATS
     287
     288DATETIME_INPUT_FORMATS
     289----------------------
     290
     291Default::
     292
     293    ('%Y-%m-%d %H:%M:%S', '%Y-%m-%d %H:%M', '%Y-%m-%d',
     294    '%m/%d/%Y %H:%M:%S', '%m/%d/%Y %H:%M', '%m/%d/%Y',
     295    '%m/%d/%y %H:%M:%S', '%m/%d/%y %H:%M', '%m/%d/%y')
     296
     297A tuple of formats that will be accepted when inputting data on a datetime
     298field. Formats will be tried in order, using the first valid.
     299Note that these format strings are specified in Python's datetime_ module
     300syntax, that is different from the one used by Django for formatting dates
     301to be displayed.
     302
     303See also ``DATE_INPUT_FORMATS`` and ``TIME_INPUT_FORMATS``.
     304
     305.. _datetime: http://docs.python.org/library/datetime.html#strftime-behavior
     306
    267307.. setting:: DEBUG
    268308
    269309DEBUG
     
    302342be useful for some test setups, and should never be used on a live
    303343site.
    304344
     345.. setting:: DECIMAL_SEPARATOR
    305346
     347DECIMAL_SEPARATOR
     348-----------------
     349
     350Default: ``'.'`` (Dot)
     351
     352Default decimal separator used when formatting decimal numbers.
     353
    306354.. setting:: DEFAULT_CHARSET
    307355
    308356DEFAULT_CHARSET
     
    528576
    529577.. _documentation for os.chmod: http://docs.python.org/lib/os-file-dir.html
    530578
     579.. setting:: FIRST_DAY_OF_WEEK
     580
     581FIRST_DAY_OF_WEEK
     582-----------------
     583
     584Default: ``0`` (Sunday)
     585
     586Number representing the first day of the week. This is specially useful
     587when displaying a calendar. This value is only used when not using
     588format internationalization, or when a format cannot be found for the
     589current locale.
     590
     591The value must be an integer from 0 to 6, where 0 means Sunday, 1 means
     592Monday and so on.
     593
    531594.. setting:: FIXTURE_DIRS
    532595
    533596FIXTURE_DIRS
     
    549612the server-provided value of ``SCRIPT_NAME``, which may be a rewritten version
    550613of the preferred value or not supplied at all.
    551614
     615.. setting:: FORMAT_MODULE_PATH
     616
     617FORMAT_MODULE_PATH
     618------------------
     619
     620Default: ``None``
     621
     622A full Python path to a Python package that contains format definitions for
     623project locales. If not ``None``, Django will check for a ``formats.py``
     624file, under the directory named as the current locale, and will use the
     625formats defined on this file.
     626
     627For example, if ``FORMAT_MODULE_PATH`` is set to ``mysite.formats``, and
     628current language is ``en`` (English), Django will expect a directory tree
     629like::
     630
     631    mysite/
     632        formats/
     633            __init__.py
     634            en/
     635                __init__.py
     636                formats.py
     637
     638Available formats are ``DATE_FORMAT``, ``TIME_FORMAT``, ``DATETIME_FORMAT``,
     639``YEAR_MONTH_FORMAT``, ``MONTH_DAY_FORMAT``, ``SHORT_DATE_FORMAT``,
     640``SHORT_DATETIME_FORMAT``, ``FIRST_DAY_OF_WEEK``, ``DECIMAL_SEPARATOR``,
     641``THOUSAND_SEPARATOR`` and ``NUMBER_GROUPING``.
     642
    552643.. setting:: IGNORABLE_404_ENDS
    553644
    554645IGNORABLE_404_ENDS
     
    774865See :ttag:`allowed date format strings <now>`. See also ``DATE_FORMAT``,
    775866``DATETIME_FORMAT``, ``TIME_FORMAT`` and ``YEAR_MONTH_FORMAT``.
    776867
     868.. setting:: NUMBER_GROUPING
     869
     870NUMBER_GROUPING
     871----------------
     872
     873Default: ``0``
     874
     875Number of digits grouped together on the integer part of a number. Common use
     876is to display a thousand separator. If this setting is ``0``, then, no grouping
     877will be applied to the number. If this setting is greater than ``0`` then the
     878setting ``THOUSAND_SEPARATOR`` will be used as the separator between those
     879groups.
     880
     881See also ``THOUSAND_SEPARATOR``
     882
    777883.. setting:: PREPEND_WWW
    778884
    779885PREPEND_WWW
     
    9651071Whether to save the session data on every request. See
    9661072:ref:`topics-http-sessions`.
    9671073
     1074.. setting:: SHORT_DATE_FORMAT
     1075
     1076SHORT_DATE_FORMAT
     1077-----------------
     1078
     1079Default: ``m/d/Y`` (e.g. ``12/31/2003``)
     1080
     1081An available formatting that can be used for date fields on templates.
     1082Note that if ``USE_FORMAT_I18N`` is set to ``True``, then locale format will
     1083be applied. See :ttag:`allowed date format strings <now>`.
     1084
     1085See also ``DATE_FORMAT`` and ``SHORT_DATETIME_FORMAT``.
     1086
     1087.. setting:: SHORT_DATETIME_FORMAT
     1088
     1089SHORT_DATETIME_FORMAT
     1090---------------------
     1091
     1092Default: ``m/d/Y P`` (e.g. ``12/31/2003 4 p.m.``)
     1093
     1094An available formatting that can be used for datetime fields on templates.
     1095Note that if ``USE_FORMAT_I18N`` is set to ``True``, then locale format will
     1096be applied. See :ttag:`allowed date format strings <now>`.
     1097
     1098See also ``DATE_FORMAT`` and ``SHORT_DATETIME_FORMAT``.
     1099
    9681100.. setting:: SITE_ID
    9691101
    9701102SITE_ID
     
    11101242
    11111243.. _Testing Django Applications: ../testing/
    11121244
     1245.. setting:: THOUSAND_SEPARATOR
     1246
     1247THOUSAND_SEPARATOR
     1248------------------
     1249
     1250Default ``,`` (Comma)
     1251
     1252Default thousand separator used when formatting numbers. This setting is
     1253used only when ``NUMBER_GROUPPING`` is set.
     1254
     1255See also ``NUMBER_GROUPPING``, ``DECIMAL_SEPARATOR``
     1256
    11131257.. setting:: TIME_FORMAT
    11141258
    11151259TIME_FORMAT
     
    11171261
    11181262Default: ``'P'`` (e.g. ``4 p.m.``)
    11191263
    1120 The default formatting to use for time fields on Django admin change-list
    1121 pages -- and, possibly, by other parts of the system. See
    1122 :ttag:`allowed date format strings <now>`.
     1264The default formatting to use for time fields in any part of the system.
     1265Note that if ``USE_FORMAT_I18N`` is set to ``True``, then locale format will
     1266be applied. See :ttag:`allowed date format strings <now>`.
    11231267
    1124 See also ``DATE_FORMAT``, ``DATETIME_FORMAT``, ``TIME_FORMAT``,
    1125 ``YEAR_MONTH_FORMAT`` and ``MONTH_DAY_FORMAT``.
     1268See also ``DATE_FORMAT`` and ``DATETIME_FORMAT``.
    11261269
     1270.. setting:: TIME_INPUT_FORMATS
     1271
     1272TIME_INPUT_FORMATS
     1273------------------
     1274
     1275Default: ``('%H:%M:%S', '%H:%M')``
     1276
     1277A tuple of formats that will be accepted when inputting data on a time
     1278field. Formats will be tried in order, using the first valid.
     1279Note that these format strings are specified in Python's datetime_ module
     1280syntax, that is different from the one used by Django for formatting dates
     1281to be displayed.
     1282
     1283See also ``DATE_INPUT_FORMATS`` and ``DATETIME_INPUT_FORMATS``.
     1284
     1285.. _datetime: http://docs.python.org/library/datetime.html#strftime-behavior
     1286
    11271287.. setting:: TIME_ZONE
    11281288
    11291289TIME_ZONE
     
    11771337bandwidth but slows down performance. This is only used if ``CommonMiddleware``
    11781338is installed (see :ref:`topics-http-middleware`).
    11791339
     1340.. setting:: USE_FORMAT_I18N
     1341
     1342USE_FORMAT_I18N
     1343---------------
     1344
     1345Default ``False``
     1346
     1347A boolean that specifies if data will be localized by default or not. If this is
     1348set to ``True``, Django will display numbers and dates using the format of the
     1349current locale. It is required to set ``USE_I18N`` to ``True`` to allow data
     1350format localization.
     1351
     1352See also ``USE_I18N``
     1353
    11801354.. setting:: USE_I18N
    11811355
    11821356USE_I18N
     
    11891363set to ``False``, Django will make some optimizations so as not to load the
    11901364internationalization machinery.
    11911365
     1366See also ``USE_FORMAT_I18N``
     1367
     1368.. setting:: USE_THOUSAND_SEPARATOR
     1369
     1370USE_THOUSAND_SEPARATOR
     1371----------------------
     1372
     1373Default ``False``
     1374
     1375A boolean that specifies wheter to display numbers using a thousand separator.
     1376If this is set to ``True``, Django will use values from ``THOUSAND_SEPARATOR``
     1377and ``NUMBER_GROUPING`` from current locale, to format the number.
     1378``USE_FORMAT_I18N`` must be set to ``True``, in order to format numbers.
     1379
     1380See also ``THOUSAND_SEPARATOR`` and ``NUMBER_GROUPING``.
     1381
    11921382.. setting:: YEAR_MONTH_FORMAT
    11931383
    11941384YEAR_MONTH_FORMAT
  • docs/ref/templates/builtins.txt

     
    897897date
    898898~~~~
    899899
    900 Formats a date according to the given format (same as the `now`_ tag).
     900Formats a date according to the given format.
    901901
     902Given format can be one of the predefined ones ``DATE_FORMAT``, ``DATETIME_FORMAT``,
     903``SHORT_DATE_FORMAT`` or ``SHORT_DATETIME_FORMAT``, or a custom format, same as the
     904`now`_ tag. Note that prefedined formats vary depending on the current locale.
     905
    902906For example::
    903907
    904908    {{ value|date:"D d M Y" }}
     
    912916    {{ value|date }}
    913917
    914918...the formatting string defined in the :setting:`DATE_FORMAT` setting will be
    915 used.
     919used, without applying any localization.
    916920
    917921.. templatefilter:: default
    918922
     
    14601464time
    14611465~~~~
    14621466
    1463 Formats a time according to the given format (same as the `now`_ tag).
     1467Formats a time according to the given format.
     1468
     1469Given format can be the predefined one ``TIME_FORMAT``, or a custom format, same as the `now`_ tag. Note that the predefined format is locale depending.
     1470
    14641471The time filter will only accept parameters in the format string that relate
    14651472to the time of day, not the date (for obvious reasons). If you need to
    14661473format a date, use the `date`_ filter.
     
    14771484    {{ value|time }}
    14781485
    14791486...the formatting string defined in the :setting:`TIME_FORMAT` setting will be
    1480 used.
     1487used, without aplying any localization.
    14811488
    14821489.. templatefilter:: timesince
    14831490
Back to Top