Ticket #7980: i18n_simple.diff
File i18n_simple.diff, 79.4 KB (added by , 15 years ago) |
---|
-
django/conf/global_settings.py
1 # -*- encoding: utf-8 -*- 1 2 # Default Django settings. Override these with settings in the module 2 3 # pointed-to by the DJANGO_SETTINGS_MODULE environment variable. 3 4 … … 75 76 ('lt', gettext_noop('Lithuanian')), 76 77 ('mk', gettext_noop('Macedonian')), 77 78 ('nl', gettext_noop('Dutch')), 78 ('n o', gettext_noop('Norwegian')),79 ('nb', gettext_noop(u'Norwegian Bokmål')), 79 80 ('pl', gettext_noop('Polish')), 80 81 ('pt', gettext_noop('Portuguese')), 81 82 ('pt-br', gettext_noop('Brazilian Portuguese')), … … 103 104 LOCALE_PATHS = () 104 105 LANGUAGE_COOKIE_NAME = 'django_language' 105 106 107 # If you set this to True, Django will format dates, numbers and calendars 108 # according to user current locale 109 USE_FORMAT_I18N = False 110 106 111 # Not-necessarily-technical managers of the site. They get broken link 107 112 # notifications and other various e-mails. 108 113 MANAGERS = ADMINS … … 255 260 # you'd pass directly to os.chmod; see http://docs.python.org/lib/os-file-dir.html. 256 261 FILE_UPLOAD_PERMISSIONS = None 257 262 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) 267 FORMAT_MODULE_PATH = None 268 258 269 # Default formatting for date objects. See all available format strings here: 259 270 # http://docs.djangoproject.com/en/dev/ref/templates/builtins/#now 260 271 DATE_FORMAT = 'N j, Y' … … 277 288 # http://docs.djangoproject.com/en/dev/ref/templates/builtins/#now 278 289 MONTH_DAY_FORMAT = 'F j' 279 290 291 # Default shortformatting for date objects. See all available format strings here: 292 # http://docs.djangoproject.com/en/dev/ref/templates/builtins/#now 293 SHORT_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 298 SHORT_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 305 DATE_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 318 TIME_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 328 DATETIME_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... 342 FIRST_DAY_OF_WEEK = 0 343 344 # Decimal separator symbol 345 DECIMAL_SEPARATOR = '.' 346 347 # Boolean that sets whether to add thousand separator when formatting numbers 348 USE_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... 352 NUMBER_GROUPING = 0 353 354 # Thousand separator symbol 355 THOUSAND_SEPARATOR = ',' 356 280 357 # Do you want to manage transactions manually? 281 358 # Hint: you really don't! 282 359 TRANSACTIONS_MANAGED = False -
django/forms/extras/widgets.py
8 8 from django.forms.widgets import Widget, Select 9 9 from django.utils.dates import MONTHS 10 10 from django.utils.safestring import mark_safe 11 from django.utils.formats import getformat 12 from django.conf import settings 11 13 12 14 __all__ = ('SelectDateWidget',) 13 15 … … 45 47 if match: 46 48 year_val, month_val, day_val = [int(v) for v in match.groups()] 47 49 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 48 59 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) 80 71 return mark_safe(u'\n'.join(output)) 81 72 82 73 def id_for_label(self, id_): … … 90 81 if y == m == d == "0": 91 82 return None 92 83 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) 94 94 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
26 26 import django.core.exceptions 27 27 from django.utils.translation import ugettext_lazy as _ 28 28 from django.utils.encoding import smart_unicode, smart_str 29 from django.utils.formats import getformat 29 30 30 31 from util import ErrorList, ValidationError 31 32 from widgets import TextInput, PasswordInput, HiddenInput, MultipleHiddenInput, FileInput, CheckboxInput, Select, NullBooleanSelect, SelectMultiple, DateInput, DateTimeInput, TimeInput, SplitDateTimeWidget, SplitHiddenDateTimeWidget … … 33 34 34 35 __all__ = ( 35 36 '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', 39 38 'RegexField', 'EmailField', 'FileField', 'ImageField', 'URLField', 40 39 'BooleanField', 'NullBooleanField', 'ChoiceField', 'MultipleChoiceField', 41 40 'ComboField', 'MultiValueField', 'FloatField', 'DecimalField', … … 210 209 if not self.required and value in EMPTY_VALUES: 211 210 return None 212 211 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'), '.')) 214 215 except (ValueError, TypeError): 215 216 raise ValidationError(self.error_messages['invalid']) 216 217 if self.max_value is not None and value > self.max_value: … … 246 247 return None 247 248 value = smart_str(value).strip() 248 249 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'), '.')) 250 253 except DecimalException: 251 254 raise ValidationError(self.error_messages['invalid']) 252 255 … … 274 277 raise ValidationError(self.error_messages['max_whole_digits'] % (self.max_digits - self.decimal_places)) 275 278 return value 276 279 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 285 280 class DateField(Field): 286 281 widget = DateInput 287 282 default_error_messages = { … … 290 285 291 286 def __init__(self, input_formats=None, *args, **kwargs): 292 287 super(DateField, self).__init__(*args, **kwargs) 293 self.input_formats = input_formats or DEFAULT_DATE_INPUT_FORMATS288 self.input_formats = input_formats 294 289 295 290 def clean(self, value): 296 291 """ … … 304 299 return value.date() 305 300 if isinstance(value, datetime.date): 306 301 return value 307 for format in self.input_formats :302 for format in self.input_formats or getformat('DATE_INPUT_FORMATS'): 308 303 try: 309 304 return datetime.date(*time.strptime(value, format)[:3]) 310 305 except ValueError: 311 306 continue 312 307 raise ValidationError(self.error_messages['invalid']) 313 308 314 DEFAULT_TIME_INPUT_FORMATS = (315 '%H:%M:%S', # '14:30:59'316 '%H:%M', # '14:30'317 )318 319 309 class TimeField(Field): 320 310 widget = TimeInput 321 311 default_error_messages = { … … 324 314 325 315 def __init__(self, input_formats=None, *args, **kwargs): 326 316 super(TimeField, self).__init__(*args, **kwargs) 327 self.input_formats = input_formats or DEFAULT_TIME_INPUT_FORMATS317 self.input_formats = input_formats 328 318 329 319 def clean(self, value): 330 320 """ … … 336 326 return None 337 327 if isinstance(value, datetime.time): 338 328 return value 339 for format in self.input_formats :329 for format in self.input_formats or getformat('TIME_INPUT_FORMATS'): 340 330 try: 341 331 return datetime.time(*time.strptime(value, format)[3:6]) 342 332 except ValueError: 343 333 continue 344 334 raise ValidationError(self.error_messages['invalid']) 345 335 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 358 336 class DateTimeField(Field): 359 337 widget = DateTimeInput 360 338 default_error_messages = { … … 363 341 364 342 def __init__(self, input_formats=None, *args, **kwargs): 365 343 super(DateTimeField, self).__init__(*args, **kwargs) 366 self.input_formats = input_formats or DEFAULT_DATETIME_INPUT_FORMATS344 self.input_formats = input_formats 367 345 368 346 def clean(self, value): 369 347 """ … … 383 361 if len(value) != 2: 384 362 raise ValidationError(self.error_messages['invalid']) 385 363 value = '%s %s' % tuple(value) 386 for format in self.input_formats :364 for format in self.input_formats or getformat('DATETIME_INPUT_FORMATS'): 387 365 try: 388 366 return datetime.datetime(*time.strptime(value, format)[:6]) 389 367 except ValueError: -
django/forms/widgets.py
15 15 from django.utils.translation import ugettext 16 16 from django.utils.encoding import StrAndUnicode, force_unicode 17 17 from django.utils.safestring import mark_safe 18 from django.utils.formats import localize 18 19 from django.utils import datetime_safe 19 20 from datetime import time 20 21 from util import flatatt … … 213 214 final_attrs = self.build_attrs(attrs, type=self.input_type, name=name) 214 215 if value != '': 215 216 # 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)) 217 218 return mark_safe(u'<input%s />' % flatatt(final_attrs)) 218 219 219 220 class TextInput(Input): -
django/core/management/commands/importcldr.py
1 import sys 2 import os 3 import re 4 from optparse import make_option, OptionParser 5 6 from django.core.management.base import LabelCommand, CommandError 7 8 try: 9 from lxml import etree 10 except ImportError: 11 raise CommandError('You need to install `python-lxml` to run this script') 12 13 FORMATS_FILE_NAME = 'formats.py' 14 FORMATS_FILE_HEADER = '''# -*- encoding: utf-8 -*- 15 # This file is distributed under the same license as the Django package. 16 # 17 18 ''' 19 20 def quote(nodes, name, locale, previous): 21 if len(nodes): 22 return "'%s'" % unicode(nodes[0].text).replace("'", "\\'") 23 else: 24 return None 25 26 def 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 74 def 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 88 FORMATS_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 152 def 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 161 def 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 203 class 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
3 3 from django.utils import importlib 4 4 from django.utils.translation import check_for_language, activate, to_locale, get_language 5 5 from django.utils.text import javascript_quote 6 from django.utils.formats import project_formats_module, django_formats_module 6 7 import os 7 8 import gettext as gettext_module 8 9 … … 32 33 response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code) 33 34 return response 34 35 36 def 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 35 55 NullSource = """ 36 56 /* gettext identity library */ 37 57 … … 185 205 else: 186 206 raise TypeError, k 187 207 csrc.sort() 188 for k, v in pdict.items():208 for k, v in pdict.items(): 189 209 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)))) 190 212 src.extend(csrc) 191 213 src.append(LibFoot) 192 214 src.append(InterPolate) 193 215 src = ''.join(src) 194 216 return http.HttpResponse(src, 'text/javascript') 217 -
django/utils/numberformat.py
1 from django.conf import settings 2 3 def 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
266 266 translation object to use. If no current translation is activated, the 267 267 message will be run through the default translation object. 268 268 """ 269 eol_message = message.replace('\r\n', '\n').replace('\r', '\n') 269 270 global _default, _active 270 271 t = _active.get(currentThread(), None) 271 272 if t is not None: 272 result = getattr(t, translation_function)( message)273 result = getattr(t, translation_function)(eol_message) 273 274 else: 274 275 if _default is None: 275 276 from django.conf import settings 276 277 _default = translation(settings.LANGUAGE_CODE) 277 result = getattr(_default, translation_function)( message)278 result = getattr(_default, translation_function)(eol_message) 278 279 if isinstance(message, SafeData): 279 280 return mark_safe(result) 280 281 return result … … 389 390 390 391 return settings.LANGUAGE_CODE 391 392 392 def get_date_formats():393 """394 Checks whether translation files provide a translation for some technical395 message ID to store date and time formats. If it doesn't contain one, the396 formats provided in the settings will be used.397 """398 from django.conf import settings399 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_FORMAT404 if datetime_format == 'DATETIME_FORMAT':405 datetime_format = settings.DATETIME_FORMAT406 if time_format == 'TIME_FORMAT':407 time_format = settings.TIME_FORMAT408 return date_format, datetime_format, time_format409 410 def get_partial_date_formats():411 """412 Checks whether translation files provide a translation for some technical413 message ID to store partial date formats. If it doesn't contain one, the414 formats provided in the settings will be used.415 """416 from django.conf import settings417 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_FORMAT421 if month_day_format == 'MONTH_DAY_FORMAT':422 month_day_format = settings.MONTH_DAY_FORMAT423 return year_month_format, month_day_format424 425 393 dot_re = re.compile(r'\S') 426 394 def blankout(src, char): 427 395 """ … … 537 505 result.append((lang, priority)) 538 506 result.sort(lambda x, y: -cmp(x[1], y[1])) 539 507 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 514 def 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 532 def 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
18 18 deactivate = deactivate_all = lambda: None 19 19 get_language = lambda: settings.LANGUAGE_CODE 20 20 get_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)23 21 check_for_language = lambda x: True 24 22 23 # date formats shouldn't be used using gettext anymore. This 24 # is kept for backward compatibility 25 25 TECHNICAL_ID_MAP = { 26 26 "DATE_WITH_TIME_FULL": settings.DATETIME_FORMAT, 27 27 "DATE_FORMAT": settings.DATE_FORMAT, … … 51 51 52 52 def get_language_from_request(request): 53 53 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. 57 get_date_formats = lambda: (settings.DATE_FORMAT, settings.DATETIME_FORMAT, settings.TIME_FORMAT) 58 get_partial_date_formats = lambda: (settings.YEAR_MONTH_FORMAT, settings.MONTH_DAY_FORMAT) -
django/utils/formats.py
1 import decimal 2 import datetime 3 4 from django.conf import settings 5 from django.utils.translation import get_language 6 from django.utils.importlib import import_module 7 from django.utils import dateformat 8 from django.utils import numberformat 9 10 def 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 22 def 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 32 def 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 47 def 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 54 def 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 66 def 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
25 25 var CalendarNamespace = { 26 26 monthsOfYear: gettext('January February March April May June July August September October November December').split(' '), 27 27 daysOfWeek: gettext('S M T W T F S').split(' '), 28 firstDayOfWeek: parseInt(gettext('FIRST_DAY_OF_WEEK')), 28 29 isLeapYear: function(year) { 29 30 return (((year % 4)==0) && ((year % 100)!=0) || ((year % 400)==0)); 30 31 }, … … 56 57 // Draw days-of-week header 57 58 var tableRow = quickElement('tr', tableBody); 58 59 for (var i = 0; i < 7; i++) { 59 quickElement('th', tableRow, CalendarNamespace.daysOfWeek[ i]);60 quickElement('th', tableRow, CalendarNamespace.daysOfWeek[(i + CalendarNamespace.firstDayOfWeek) % 7]); 60 61 } 61 62 62 var startingPos = new Date(year, month-1, 1 ).getDay();63 var startingPos = new Date(year, month-1, 1 - CalendarNamespace.firstDayOfWeek).getDay(); 63 64 var days = CalendarNamespace.getDaysInMonth(month, year); 64 65 65 66 // Draw blanks before first of month -
django/contrib/admin/templatetags/admin_list.py
3 3 from django.contrib.admin.views.main import ORDER_VAR, ORDER_TYPE_VAR, PAGE_VAR, SEARCH_VAR 4 4 from django.core.exceptions import ObjectDoesNotExist 5 5 from django.db import models 6 from django.utils import dateformat6 from django.utils import formats 7 7 from django.utils.html import escape, conditional_escape 8 8 from django.utils.text import capfirst 9 9 from django.utils.safestring import mark_safe 10 from django.utils.translation import get_date_formats, get_partial_date_formats,ugettext as _10 from django.utils.translation import ugettext as _ 11 11 from django.utils.encoding import smart_unicode, smart_str, force_unicode 12 12 from django.template import Library 13 13 import datetime … … 184 184 # Dates and times are special: They're formatted in a certain way. 185 185 elif isinstance(f, models.DateField) or isinstance(f, models.TimeField): 186 186 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) 194 188 else: 195 189 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 196 195 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"' 197 202 # Booleans are special: We use images. 198 203 elif isinstance(f, models.BooleanField) or isinstance(f, models.NullBooleanField): 199 204 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_val204 else:205 result_repr = EMPTY_CHANGELIST_VALUE206 205 # Fields with choices are special: Use the representation 207 206 # of the choice. 208 207 elif f.flatchoices: … … 263 262 year_lookup = cl.params.get(year_field) 264 263 month_lookup = cl.params.get(month_field) 265 264 day_lookup = cl.params.get(day_field) 266 year_month_format, month_day_format = get_partial_date_formats()267 265 268 266 link = lambda d: mark_safe(cl.get_query_string(d, [field_generic])) 269 267 … … 273 271 'show': True, 274 272 'back': { 275 273 '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')) 277 275 }, 278 'choices': [{'title': dateformat.format(day, month_day_format)}]276 'choices': [{'title': capfirst(formats.date_format(day, 'MONTH_DAY_FORMAT'))}] 279 277 } 280 278 elif year_lookup and month_lookup: 281 279 days = cl.query_set.filter(**{year_field: year_lookup, month_field: month_lookup}).dates(field_name, 'day') … … 287 285 }, 288 286 'choices': [{ 289 287 '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')) 291 289 } for day in days] 292 290 } 293 291 elif year_lookup: … … 300 298 }, 301 299 'choices': [{ 302 300 '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')) 304 302 } for month in months] 305 303 } 306 304 else: -
django/contrib/admin/templates/admin/object_history.html
27 27 <tbody> 28 28 {% for action in action_list %} 29 29 <tr> 30 <th scope="row">{{ action.action_time|date :_("DATETIME_FORMAT")}}</th>30 <th scope="row">{{ action.action_time|date }}</th> 31 31 <td>{{ action.user.username }}{% if action.user.get_full_name %} ({{ action.user.get_full_name }}){% endif %}</td> 32 32 <td>{{ action.change_message }}</td> 33 33 </tr> -
django/contrib/databrowse/datastructures.py
4 4 """ 5 5 6 6 from django.db import models 7 from django.utils import dateformat7 from django.utils import formats 8 8 from django.utils.text import capfirst 9 from django.utils.translation import get_date_formats10 9 from django.utils.encoding import smart_unicode, smart_str, iri_to_uri 11 10 from django.utils.safestring import mark_safe 12 11 from django.db.models.query import QuerySet … … 156 155 objs = dict(self.field.choices).get(self.raw_value, EMPTY_VALUE) 157 156 elif isinstance(self.field, models.DateField) or isinstance(self.field, models.TimeField): 158 157 if self.raw_value: 159 date_format, datetime_format, time_format = get_date_formats()160 158 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')) 162 160 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')) 164 162 else: 165 objs = capfirst( dateformat.format(self.raw_value, date_format))163 objs = capfirst(formats.date_format(self.raw_value, 'DATE_FORMAT')) 166 164 else: 167 165 objs = EMPTY_VALUE 168 166 elif isinstance(self.field, models.BooleanField) or isinstance(self.field, models.NullBooleanField): -
django/template/defaultfilters.py
18 18 from django.utils.translation import ugettext, ungettext 19 19 from django.utils.encoding import force_unicode, iri_to_uri 20 20 from django.utils.safestring import mark_safe, SafeData 21 from django.utils.formats import date_format, number_format 21 22 22 23 register = Library() 23 24 … … 166 167 return input_val 167 168 168 169 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)) 170 171 171 172 if p == 0: 172 173 exp = Decimal(1) 173 174 else: 174 175 exp = Decimal('1.0') / (Decimal(10) ** abs(p)) 175 176 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))) 177 178 except InvalidOperation: 178 179 return input_val 179 180 floatformat.is_safe = True … … 684 685 if arg is None: 685 686 arg = settings.DATE_FORMAT 686 687 try: 687 return format(value, arg)688 return date_format(value, arg) 688 689 except AttributeError: 689 return '' 690 try: 691 return format(value, arg) 692 except AttributeError: 693 return '' 690 694 date.is_safe = False 691 695 692 696 def time(value, arg=None): … … 697 701 if arg is None: 698 702 arg = settings.TIME_FORMAT 699 703 try: 700 return time_format(value, arg)704 return date_format(value, arg) 701 705 except AttributeError: 702 return '' 706 try: 707 return time_format(value, arg) 708 except AttributeError: 709 return '' 703 710 time.is_safe = False 704 711 705 712 def timesince(value, arg=None): -
django/template/__init__.py
60 60 from django.utils.encoding import smart_unicode, force_unicode, smart_str 61 61 from django.utils.translation import ugettext as _ 62 62 from django.utils.safestring import SafeData, EscapeData, mark_safe, mark_for_escaping 63 from django.utils.formats import localize 63 64 from django.utils.html import escape 64 65 65 66 __all__ = ('Template', 'Context', 'RequestContext', 'compile_string') … … 808 809 means escaping, if required, and conversion to a unicode object. If value 809 810 is a string, it is expected to have already been translated. 810 811 """ 812 value = localize(value) 811 813 value = force_unicode(value) 812 814 if (context.autoescape and not isinstance(value, SafeData)) or isinstance(value, EscapeData): 813 815 return escape(value) -
django/template/debug.py
2 2 from django.utils.encoding import force_unicode 3 3 from django.utils.html import escape 4 4 from django.utils.safestring import SafeData, EscapeData 5 from django.utils.formats import localize 5 6 6 7 class DebugLexer(Lexer): 7 8 def __init__(self, template_string, origin): … … 84 85 class DebugVariableNode(VariableNode): 85 86 def render(self, context): 86 87 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) 88 91 except TemplateSyntaxError, e: 89 92 if not hasattr(e, 'source'): 90 93 e.source = self.source -
tests/regressiontests/i18n/tests.py
64 64 'as' 65 65 >>> print s 66 66 Password 67 68 Translations on files with mac or dos end of lines will be converted 69 to 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') 77 u'Catalan Mac\nEOF\n' 78 >>> ugettext(u'Win\r\nEOF\r\n') 79 u'Catalan Win\nEOF\n' 80 >>> deactivate() 81 82 Localization 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 111 Locale 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=',') 116 u'66666.66' 117 >>> format(n, decimal_sep='A', decimal_pos=1, grouping=1, thousand_sep='B') 118 u'66666A6' 119 >>> settings.USE_THOUSAND_SEPARATOR = True 120 >>> format(n, decimal_sep='.', decimal_pos=2, grouping=3, thousand_sep=',') 121 u'66,666.66' 122 >>> format(n, decimal_sep='A', decimal_pos=1, grouping=1, thousand_sep='B') 123 u'6B6B6B6B6A6' 124 125 Catalan locale with format i18n disabled 126 translations 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') 133 0 134 >>> getformat('DECIMAL_SEPARATOR') 135 '.' 136 >>> date_format(d) 137 u'des. 31, 2009' 138 >>> date_format(d, 'YEAR_MONTH_FORMAT') 139 u'desembre 2009' 140 >>> date_format(dt, 'SHORT_DATETIME_FORMAT') 141 u'12/31/2009 8:50 p.m.' 142 >>> localize('No localizable') 143 'No localizable' 144 >>> localize(n) 145 Decimal('66666.666') 146 >>> localize(f) 147 99999.999 148 >>> localize(d) 149 datetime.date(2009, 12, 31) 150 >>> localize(dt) 151 datetime.datetime(2009, 12, 31, 20, 50) 152 >>> template.Template('{{ n }}').render(ctxt) 153 u'66666.666' 154 >>> template.Template('{{ f }}').render(ctxt) 155 u'99999.999' 156 >>> template.Template('{{ d }}').render(ctxt) 157 u'2009-12-31' 158 >>> template.Template('{{ dt }}').render(ctxt) 159 u'2009-12-31 20:50:00' 160 >>> template.Template('{{ n|floatformat:2 }}').render(ctxt) 161 u'66666.67' 162 >>> template.Template('{{ f|floatformat }}').render(ctxt) 163 u'100000.0' 164 >>> template.Template('{{ d|date:"SHORT_DATE_FORMAT" }}').render(ctxt) 165 u'12/31/2009' 166 >>> template.Template('{{ dt|date:"SHORT_DATETIME_FORMAT" }}').render(ctxt) 167 u'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() 170 False 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() 181 True 182 >>> form2.cleaned_data['date_field'] 183 datetime.date(2009, 12, 31) 184 >>> SelectDateWidget().render('mydate', datetime.date(2009, 12, 31)) 185 u'<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 187 Catalan 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') 194 1 195 >>> getformat('DECIMAL_SEPARATOR') 196 ',' 197 >>> date_format(d) 198 u'31 de desembre de 2009' 199 >>> date_format(d, 'YEAR_MONTH_FORMAT') 200 u'desembre del 2009' 201 >>> date_format(dt, 'SHORT_DATETIME_FORMAT') 202 u'31/12/2009 20:50' 203 >>> localize('No localizable') 204 'No localizable' 205 >>> settings.USE_THOUSAND_SEPARATOR = True 206 >>> localize(n) 207 u'66.666,666' 208 >>> localize(f) 209 u'99.999,999' 210 >>> settings.USE_THOUSAND_SEPARATOR = False 211 >>> localize(n) 212 u'66666,666' 213 >>> localize(f) 214 u'99999,999' 215 >>> localize(d) 216 u'31 de desembre de 2009' 217 >>> localize(dt) 218 u'31 de desembre de 2009 a les 20:50' 219 >>> settings.USE_THOUSAND_SEPARATOR = True 220 >>> template.Template('{{ n }}').render(ctxt) 221 u'66.666,666' 222 >>> template.Template('{{ f }}').render(ctxt) 223 u'99.999,999' 224 >>> settings.USE_THOUSAND_SEPARATOR = False 225 >>> template.Template('{{ n }}').render(ctxt) 226 u'66666,666' 227 >>> template.Template('{{ f }}').render(ctxt) 228 u'99999,999' 229 >>> template.Template('{{ d }}').render(ctxt) 230 u'31 de desembre de 2009' 231 >>> template.Template('{{ dt }}').render(ctxt) 232 u'31 de desembre de 2009 a les 20:50' 233 >>> template.Template('{{ n|floatformat:2 }}').render(ctxt) 234 u'66666,67' 235 >>> template.Template('{{ f|floatformat }}').render(ctxt) 236 u'100000,0' 237 >>> template.Template('{{ d|date:"SHORT_DATE_FORMAT" }}').render(ctxt) 238 u'31/12/2009' 239 >>> template.Template('{{ dt|date:"SHORT_DATETIME_FORMAT" }}').render(ctxt) 240 u'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() 243 True 244 >>> form.cleaned_data['decimal_field'] 245 Decimal('66666.666') 246 >>> form.cleaned_data['float_field'] 247 99999.999 248 >>> form.cleaned_data['date_field'] 249 datetime.date(2009, 12, 31) 250 >>> form.cleaned_data['datetime_field'] 251 datetime.datetime(2009, 12, 31, 20, 50) 252 >>> form.cleaned_data['time_field'] 253 datetime.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() 256 True 257 >>> form2.cleaned_data['date_field'] 258 datetime.date(2009, 12, 31) 259 >>> SelectDateWidget().render('mydate', datetime.date(2009, 12, 31)) 260 u'<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 262 English 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') 269 0 270 >>> getformat('DECIMAL_SEPARATOR') 271 '.' 272 >>> date_format(d) 273 u'Dec. 31, 2009' 274 >>> date_format(d, 'YEAR_MONTH_FORMAT') 275 u'December 2009' 276 >>> date_format(dt, 'SHORT_DATETIME_FORMAT') 277 u'12/31/2009 8:50 p.m.' 278 >>> localize('No localizable') 279 'No localizable' 280 >>> settings.USE_THOUSAND_SEPARATOR = True 281 >>> localize(n) 282 u'66,666.666' 283 >>> localize(f) 284 u'99,999.999' 285 >>> settings.USE_THOUSAND_SEPARATOR = False 286 >>> localize(n) 287 u'66666.666' 288 >>> localize(f) 289 u'99999.999' 290 >>> localize(d) 291 u'Dec. 31, 2009' 292 >>> localize(dt) 293 u'Dec. 31, 2009, 8:50 p.m.' 294 >>> settings.USE_THOUSAND_SEPARATOR = True 295 >>> template.Template('{{ n }}').render(ctxt) 296 u'66,666.666' 297 >>> template.Template('{{ f }}').render(ctxt) 298 u'99,999.999' 299 >>> settings.USE_THOUSAND_SEPARATOR = False 300 >>> template.Template('{{ n }}').render(ctxt) 301 u'66666.666' 302 >>> template.Template('{{ f }}').render(ctxt) 303 u'99999.999' 304 >>> template.Template('{{ d }}').render(ctxt) 305 u'Dec. 31, 2009' 306 >>> template.Template('{{ dt }}').render(ctxt) 307 u'Dec. 31, 2009, 8:50 p.m.' 308 >>> template.Template('{{ n|floatformat:2 }}').render(ctxt) 309 u'66666.67' 310 >>> template.Template('{{ f|floatformat }}').render(ctxt) 311 u'100000.0' 312 >>> template.Template('{{ d|date:"SHORT_DATE_FORMAT" }}').render(ctxt) 313 u'12/31/2009' 314 >>> template.Template('{{ dt|date:"SHORT_DATETIME_FORMAT" }}').render(ctxt) 315 u'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() 318 True 319 >>> form.cleaned_data['decimal_field'] 320 Decimal('66666.666') 321 >>> form.cleaned_data['float_field'] 322 99999.999 323 >>> form.cleaned_data['date_field'] 324 datetime.date(2009, 12, 31) 325 >>> form.cleaned_data['datetime_field'] 326 datetime.datetime(2009, 12, 31, 20, 50) 327 >>> form.cleaned_data['time_field'] 328 datetime.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() 331 True 332 >>> form2.cleaned_data['date_field'] 333 datetime.date(2009, 12, 31) 334 >>> SelectDateWidget().render('mydate', datetime.date(2009, 12, 31)) 335 u'<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 337 Restore 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 67 344 """ 68 345 69 346 __test__ = { -
docs/topics/i18n.txt
4 4 Internationalization 5 5 ==================== 6 6 7 Django has full support for internationalization of text in code and templates. 8 Here's how it works. 7 Django has full support for internationalization, including translation 8 capabilities of text in code and templates, and format localization for 9 dates and numbers. Here's how it works. 9 10 10 11 Overview 11 12 ======== 12 13 13 14 The goal of internationalization is to allow a single Web application to offer 14 its content and functionality in multiple languages .15 its content and functionality in multiple languages and locales. 15 16 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 t he end user's language, if a translation for this text is available in that20 language."17 For text translation, you, the Django developer, can accomplish this goal by 18 adding a minimal amount of hooks to your Python code and templates. These hooks 19 are called **translation strings**. They tell Django: "This text should be 20 translated into the end user's language, if a translation for this text is 21 available in that language." 21 22 22 23 Django takes care of using these hooks to translate Web apps, on the fly, 23 24 according to users' language preferences. … … 29 30 * It uses these hooks to translate Web apps for particular users according 30 31 to their language preferences. 31 32 33 For 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 36 numbers and dates in the format of the current locale. That includes field 37 representation on templates, and allowed input formats on the admin. 38 32 39 If you don't need internationalization in your app 33 40 ================================================== 34 41 … … 1074 1081 translation utilities with a ``gettext`` package if the command ``xgettext 1075 1082 --version`` entered at a Windows command prompt causes a popup window saying 1076 1083 "xgettext.exe has generated errors and will be closed by Windows". 1084 1085 Format localization 1086 =================== 1087 1088 Django's formatting system is disabled by default. To enable it, it's necessay 1089 to set :setting:`USE_FORMAT_I18N = True <USE_FORMAT_I18N>` in your settings 1090 file. Note that :setting:`USE_FORMAT_I18N` requires `USE_I18N` to be ``True``. 1091 1092 When using Django's formatting system, dates and numbers on templates will be 1093 displayed using the format specified for the current locale. That means, two 1094 users accessing the same content, but in different language, will see date and 1095 number fields formatted in different ways, depending on the format for their 1096 current locale. 1097 1098 Django will also use localized formats when parsing data in forms. That means 1099 Django uses different formats for different locales when guessing the format 1100 used by the user when inputting data on forms. Note that Django uses different 1101 formats for displaying data, and for parsing it. 1102 1103 Creating custom format files 1104 ---------------------------- 1105 1106 Django provides format definitions for many locales, but sometimes you could 1107 want to create your own ones, because a format files doesn't exist for your 1108 locale, or because you want to overwrite some of the values. 1109 1110 To use custom formats, first thing to do, is to specify the path where you'll 1111 place format files. To do that, just set :setting:`FORMAT_MODULE_PATH` setting 1112 to the the path (in the format ``'foo.bar.baz``) where format files will 1113 exists. 1114 1115 Files are not placed directly in this directory, but in a directory named as 1116 the locale. File must be named ``formats.py``. 1117 1118 For 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 1127 where :file:`formats.py` contains custom format definitions. For example:: 1128 1129 THOUSAND_SEPARATOR = ' ' 1130 1131 to use a space as thousand separator, instead of the default for English, 1132 comma. 1133 -
docs/ref/settings.txt
243 243 244 244 Default: ``'N j, Y'`` (e.g. ``Feb. 4, 2003``) 245 245 246 The default formatting to use for date fields on Django admin change-list247 pages -- and, possibly, by other parts of the system. See 248 :ttag:`allowed date format strings <now>`.246 The default formatting to use for date fields in any part of the system. 247 Note that if ``USE_FORMAT_I18N`` is set to ``True``, then locale format will 248 be applied. See :ttag:`allowed date format strings <now>`. 249 249 250 See also ``DATETIME_FORMAT``, ``TIME_FORMAT``, ``YEAR_MONTH_FORMAT`` 251 and ``MONTH_DAY_FORMAT``. 250 See also ``DATETIME_FORMAT``, ``TIME_FORMAT`` and ``SHORT_DATE_FORMAT``. 252 251 252 .. setting:: DATE_INPUT_FORMATS 253 254 DATE_INPUT_FORMATS 255 ------------------ 256 257 Default:: 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 263 A tuple of formats that will be accepted when inputting data on a date 264 field. Formats will be tried in order, using the first valid. 265 Note that these format strings are specified in Python's datetime_ module 266 syntax, that is different from the one used by Django for formatting dates 267 to be displayed. 268 269 See also ``DATETIME_INPUT_FORMATS`` and ``TIME_INPUT_FORMATS``. 270 271 .. _datetime: http://docs.python.org/library/datetime.html#strftime-behavior 272 253 273 .. setting:: DATETIME_FORMAT 254 274 255 275 DATETIME_FORMAT … … 257 277 258 278 Default: ``'N j, Y, P'`` (e.g. ``Feb. 4, 2003, 4 p.m.``) 259 279 260 The default formatting to use for datetime fields on Django admin change-list261 pages -- and, possibly, by other parts of the system. See 262 :ttag:`allowed date format strings <now>`.280 The default formatting to use for datetime fields in any part of the system. 281 Note that if ``USE_FORMAT_I18N`` is set to ``True``, then locale format will 282 be applied. See :ttag:`allowed date format strings <now>`. 263 283 264 See also ``DATE_FORMAT``, ``DATETIME_FORMAT``, ``TIME_FORMAT``, 265 ``YEAR_MONTH_FORMAT`` and ``MONTH_DAY_FORMAT``. 284 See also ``DATE_FORMAT``, ``TIME_FORMAT`` and ``SHORT_DATETIME_FORMAT``. 266 285 286 .. setting:: DATETIME_INPUT_FORMATS 287 288 DATETIME_INPUT_FORMATS 289 ---------------------- 290 291 Default:: 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 297 A tuple of formats that will be accepted when inputting data on a datetime 298 field. Formats will be tried in order, using the first valid. 299 Note that these format strings are specified in Python's datetime_ module 300 syntax, that is different from the one used by Django for formatting dates 301 to be displayed. 302 303 See also ``DATE_INPUT_FORMATS`` and ``TIME_INPUT_FORMATS``. 304 305 .. _datetime: http://docs.python.org/library/datetime.html#strftime-behavior 306 267 307 .. setting:: DEBUG 268 308 269 309 DEBUG … … 302 342 be useful for some test setups, and should never be used on a live 303 343 site. 304 344 345 .. setting:: DECIMAL_SEPARATOR 305 346 347 DECIMAL_SEPARATOR 348 ----------------- 349 350 Default: ``'.'`` (Dot) 351 352 Default decimal separator used when formatting decimal numbers. 353 306 354 .. setting:: DEFAULT_CHARSET 307 355 308 356 DEFAULT_CHARSET … … 528 576 529 577 .. _documentation for os.chmod: http://docs.python.org/lib/os-file-dir.html 530 578 579 .. setting:: FIRST_DAY_OF_WEEK 580 581 FIRST_DAY_OF_WEEK 582 ----------------- 583 584 Default: ``0`` (Sunday) 585 586 Number representing the first day of the week. This is specially useful 587 when displaying a calendar. This value is only used when not using 588 format internationalization, or when a format cannot be found for the 589 current locale. 590 591 The value must be an integer from 0 to 6, where 0 means Sunday, 1 means 592 Monday and so on. 593 531 594 .. setting:: FIXTURE_DIRS 532 595 533 596 FIXTURE_DIRS … … 549 612 the server-provided value of ``SCRIPT_NAME``, which may be a rewritten version 550 613 of the preferred value or not supplied at all. 551 614 615 .. setting:: FORMAT_MODULE_PATH 616 617 FORMAT_MODULE_PATH 618 ------------------ 619 620 Default: ``None`` 621 622 A full Python path to a Python package that contains format definitions for 623 project locales. If not ``None``, Django will check for a ``formats.py`` 624 file, under the directory named as the current locale, and will use the 625 formats defined on this file. 626 627 For example, if ``FORMAT_MODULE_PATH`` is set to ``mysite.formats``, and 628 current language is ``en`` (English), Django will expect a directory tree 629 like:: 630 631 mysite/ 632 formats/ 633 __init__.py 634 en/ 635 __init__.py 636 formats.py 637 638 Available 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 552 643 .. setting:: IGNORABLE_404_ENDS 553 644 554 645 IGNORABLE_404_ENDS … … 774 865 See :ttag:`allowed date format strings <now>`. See also ``DATE_FORMAT``, 775 866 ``DATETIME_FORMAT``, ``TIME_FORMAT`` and ``YEAR_MONTH_FORMAT``. 776 867 868 .. setting:: NUMBER_GROUPING 869 870 NUMBER_GROUPING 871 ---------------- 872 873 Default: ``0`` 874 875 Number of digits grouped together on the integer part of a number. Common use 876 is to display a thousand separator. If this setting is ``0``, then, no grouping 877 will be applied to the number. If this setting is greater than ``0`` then the 878 setting ``THOUSAND_SEPARATOR`` will be used as the separator between those 879 groups. 880 881 See also ``THOUSAND_SEPARATOR`` 882 777 883 .. setting:: PREPEND_WWW 778 884 779 885 PREPEND_WWW … … 965 1071 Whether to save the session data on every request. See 966 1072 :ref:`topics-http-sessions`. 967 1073 1074 .. setting:: SHORT_DATE_FORMAT 1075 1076 SHORT_DATE_FORMAT 1077 ----------------- 1078 1079 Default: ``m/d/Y`` (e.g. ``12/31/2003``) 1080 1081 An available formatting that can be used for date fields on templates. 1082 Note that if ``USE_FORMAT_I18N`` is set to ``True``, then locale format will 1083 be applied. See :ttag:`allowed date format strings <now>`. 1084 1085 See also ``DATE_FORMAT`` and ``SHORT_DATETIME_FORMAT``. 1086 1087 .. setting:: SHORT_DATETIME_FORMAT 1088 1089 SHORT_DATETIME_FORMAT 1090 --------------------- 1091 1092 Default: ``m/d/Y P`` (e.g. ``12/31/2003 4 p.m.``) 1093 1094 An available formatting that can be used for datetime fields on templates. 1095 Note that if ``USE_FORMAT_I18N`` is set to ``True``, then locale format will 1096 be applied. See :ttag:`allowed date format strings <now>`. 1097 1098 See also ``DATE_FORMAT`` and ``SHORT_DATETIME_FORMAT``. 1099 968 1100 .. setting:: SITE_ID 969 1101 970 1102 SITE_ID … … 1110 1242 1111 1243 .. _Testing Django Applications: ../testing/ 1112 1244 1245 .. setting:: THOUSAND_SEPARATOR 1246 1247 THOUSAND_SEPARATOR 1248 ------------------ 1249 1250 Default ``,`` (Comma) 1251 1252 Default thousand separator used when formatting numbers. This setting is 1253 used only when ``NUMBER_GROUPPING`` is set. 1254 1255 See also ``NUMBER_GROUPPING``, ``DECIMAL_SEPARATOR`` 1256 1113 1257 .. setting:: TIME_FORMAT 1114 1258 1115 1259 TIME_FORMAT … … 1117 1261 1118 1262 Default: ``'P'`` (e.g. ``4 p.m.``) 1119 1263 1120 The default formatting to use for time fields on Django admin change-list1121 pages -- and, possibly, by other parts of the system. See 1122 :ttag:`allowed date format strings <now>`.1264 The default formatting to use for time fields in any part of the system. 1265 Note that if ``USE_FORMAT_I18N`` is set to ``True``, then locale format will 1266 be applied. See :ttag:`allowed date format strings <now>`. 1123 1267 1124 See also ``DATE_FORMAT``, ``DATETIME_FORMAT``, ``TIME_FORMAT``, 1125 ``YEAR_MONTH_FORMAT`` and ``MONTH_DAY_FORMAT``. 1268 See also ``DATE_FORMAT`` and ``DATETIME_FORMAT``. 1126 1269 1270 .. setting:: TIME_INPUT_FORMATS 1271 1272 TIME_INPUT_FORMATS 1273 ------------------ 1274 1275 Default: ``('%H:%M:%S', '%H:%M')`` 1276 1277 A tuple of formats that will be accepted when inputting data on a time 1278 field. Formats will be tried in order, using the first valid. 1279 Note that these format strings are specified in Python's datetime_ module 1280 syntax, that is different from the one used by Django for formatting dates 1281 to be displayed. 1282 1283 See also ``DATE_INPUT_FORMATS`` and ``DATETIME_INPUT_FORMATS``. 1284 1285 .. _datetime: http://docs.python.org/library/datetime.html#strftime-behavior 1286 1127 1287 .. setting:: TIME_ZONE 1128 1288 1129 1289 TIME_ZONE … … 1177 1337 bandwidth but slows down performance. This is only used if ``CommonMiddleware`` 1178 1338 is installed (see :ref:`topics-http-middleware`). 1179 1339 1340 .. setting:: USE_FORMAT_I18N 1341 1342 USE_FORMAT_I18N 1343 --------------- 1344 1345 Default ``False`` 1346 1347 A boolean that specifies if data will be localized by default or not. If this is 1348 set to ``True``, Django will display numbers and dates using the format of the 1349 current locale. It is required to set ``USE_I18N`` to ``True`` to allow data 1350 format localization. 1351 1352 See also ``USE_I18N`` 1353 1180 1354 .. setting:: USE_I18N 1181 1355 1182 1356 USE_I18N … … 1189 1363 set to ``False``, Django will make some optimizations so as not to load the 1190 1364 internationalization machinery. 1191 1365 1366 See also ``USE_FORMAT_I18N`` 1367 1368 .. setting:: USE_THOUSAND_SEPARATOR 1369 1370 USE_THOUSAND_SEPARATOR 1371 ---------------------- 1372 1373 Default ``False`` 1374 1375 A boolean that specifies wheter to display numbers using a thousand separator. 1376 If this is set to ``True``, Django will use values from ``THOUSAND_SEPARATOR`` 1377 and ``NUMBER_GROUPING`` from current locale, to format the number. 1378 ``USE_FORMAT_I18N`` must be set to ``True``, in order to format numbers. 1379 1380 See also ``THOUSAND_SEPARATOR`` and ``NUMBER_GROUPING``. 1381 1192 1382 .. setting:: YEAR_MONTH_FORMAT 1193 1383 1194 1384 YEAR_MONTH_FORMAT -
docs/ref/templates/builtins.txt
897 897 date 898 898 ~~~~ 899 899 900 Formats a date according to the given format (same as the `now`_ tag).900 Formats a date according to the given format. 901 901 902 Given 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 902 906 For example:: 903 907 904 908 {{ value|date:"D d M Y" }} … … 912 916 {{ value|date }} 913 917 914 918 ...the formatting string defined in the :setting:`DATE_FORMAT` setting will be 915 used .919 used, without applying any localization. 916 920 917 921 .. templatefilter:: default 918 922 … … 1460 1464 time 1461 1465 ~~~~ 1462 1466 1463 Formats a time according to the given format (same as the `now`_ tag). 1467 Formats a time according to the given format. 1468 1469 Given 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 1464 1471 The time filter will only accept parameters in the format string that relate 1465 1472 to the time of day, not the date (for obvious reasons). If you need to 1466 1473 format a date, use the `date`_ filter. … … 1477 1484 {{ value|time }} 1478 1485 1479 1486 ...the formatting string defined in the :setting:`TIME_FORMAT` setting will be 1480 used .1487 used, without aplying any localization. 1481 1488 1482 1489 .. templatefilter:: timesince 1483 1490