Anonymous avatar Anonymous committed e18d768

[soc2009/i18n] moving all format localization from models to templates, and code clean up

Comments (0)

Files changed (7)

django/contrib/admin/templatetags/admin_list.py

 from django.utils.text import capfirst
 from django.utils.safestring import mark_safe
 from django.utils.translation import ugettext as _
-from django.utils.formats import getformat
+from django.utils.formats import localize
 from django.utils.encoding import smart_unicode, smart_str, force_unicode
 from django.template import Library
 import datetime
                 else:
                     result_repr = EMPTY_CHANGELIST_VALUE
             # Dates and times are special: They're formatted in a certain way.
-            elif isinstance(f, models.DateField) or isinstance(f, models.TimeField):
+            elif isinstance(f, models.DateField) or isinstance(f, models.TimeField) or isinstance(f, models.DecimalField):
                 if field_val:
-                    if isinstance(f, models.DateTimeField):
-                        result_repr = capfirst(formats.date_and_time_format(field_val, 'DATETIME_FORMAT'))
-                    elif isinstance(f, models.TimeField):
-                        result_repr = capfirst(formats.date_and_time_format(field_val, 'TIME_FORMAT'))
-                    else:
-                        result_repr = capfirst(formats.format(field_val, 'DATE_FORMAT'))
+                    result_repr = localize(field_val)
+                    # result_repr = ('%%.%sf' % f.decimal_places) % field_val
                 else:
                     result_repr = EMPTY_CHANGELIST_VALUE
-                row_class = ' class="nowrap"'
+                if not isinstance(f, models.DecimalField):
+                    row_class = ' class="nowrap"'
             # Booleans are special: We use images.
             elif isinstance(f, models.BooleanField) or isinstance(f, models.NullBooleanField):
                 result_repr = _boolean_icon(field_val)
-            # DecimalFields are special: Zero-pad the decimals.
-            elif isinstance(f, models.DecimalField):
-                if field_val is not None:
-                    result_repr = ('%%.%sf' % f.decimal_places) % field_val
-                else:
-                    result_repr = EMPTY_CHANGELIST_VALUE
             # Fields with choices are special: Use the representation
             # of the choice.
             elif f.flatchoices:
                 'show': True,
                 'back': {
                     'link': link({year_field: year_lookup, month_field: month_lookup}),
-                    'title': formats.date_and_time_format(day, 'YEAR_MONTH_FORMAT')
+                    'title': capfirst(formats.date_format(day, 'YEAR_MONTH_FORMAT'))
                 },
-                'choices': [{'title': formats.date_and_time_format(day, 'MONTH_DAY_FORMAT')}]
+                'choices': [{'title': capfirst(formats.date_format(day, 'MONTH_DAY_FORMAT'))}]
             }
         elif year_lookup and month_lookup:
             days = cl.query_set.filter(**{year_field: year_lookup, month_field: month_lookup}).dates(field_name, 'day')
                 },
                 'choices': [{
                     'link': link({year_field: year_lookup, month_field: month_lookup, day_field: day.day}),
-                    'title': formats.date_and_time_format(day, 'MONTH_DAY_FORMAT')
+                    'title': capfirst(formats.date_format(day, 'MONTH_DAY_FORMAT'))
                 } for day in days]
             }
         elif year_lookup:
                 },
                 'choices': [{
                     'link': link({year_field: year_lookup, month_field: month.month}),
-                    'title': formats.date_and_time_format(month, 'YEAR_MONTH_FORMAT')
+                    'title': capfirst(formats.date_format(month, 'YEAR_MONTH_FORMAT'))
                 } for month in months]
             }
         else:

django/contrib/databrowse/datastructures.py

         elif isinstance(self.field, models.DateField) or isinstance(self.field, models.TimeField):
             if self.raw_value:
                 if isinstance(self.field, models.DateTimeField):
-                    objs = capfirst(formats.date_and_time_format(self.raw_value, 'DATETIME_FORMAT'))
+                    objs = capfirst(formats.date_format(self.raw_value, 'DATETIME_FORMAT'))
                 elif isinstance(self.field, models.TimeField):
-                    objs = capfirst(formats.date_and_time_format(self.raw_value, 'TIME_FORMAT'))
+                    objs = capfirst(formats.date_format(self.raw_value, 'TIME_FORMAT'))
                 else:
-                    objs = capfirst(formats.date_and_time_format(self.raw_value, 'DATE_FORMAT'))
+                    objs = capfirst(formats.date_format(self.raw_value, 'DATE_FORMAT'))
             else:
                 objs = EMPTY_VALUE
         elif isinstance(self.field, models.BooleanField) or isinstance(self.field, models.NullBooleanField):

django/db/models/base.py

             # is *not* consumed. We rely on this, so don't change the order
             # without changing the logic.
             for val, field in izip(args, fields_iter):
-                setattr(self, field.attname, field.localize(val))
+                setattr(self, field.attname, val)
         else:
             # Slower, kwargs-ready version.
             for val, field in izip(args, fields_iter):
-                setattr(self, field.attname, field.localize(val))
+                setattr(self, field.attname, val)
                 kwargs.pop(field.name, None)
                 # Maintain compatibility with existing calls.
                 if isinstance(field.rel, ManyToOneRel):

django/db/models/fields/__init__.py

         "Returns the value of this field in the given model instance."
         return getattr(obj, self.attname)
 
-    def localize(self, value):
-        """
-        Returns the value with a localize method that can be used when
-        representing the object as a string, to get the value formatted
-        using the current locale
-        """
-        # FIXME: is there a way to to cast an instance to a class that works for
-        # datetime.datetime objects?
-        import datetime
-        localized_class = type('localized_class', (type(value),), dict(localize=None))
-        if isinstance(value, datetime.date):
-            localized_value = localized_class(value.year, value.month, value.day)
-        elif isinstance(value, datetime.datetime):
-            localized_value = localized_class(value.year, value.month, value.day,
-                value.hour, value.minute, value.second)
-        else:
-            localized_value = localized_class(value)
-
-        localized_value.localize = lambda : self._localize_funct(value)
-        return localized_value
-
-    def _localize_funct(self, value):
-        """
-        Localizable field types should overwrite this method to specify
-        how to localize field representation
-        """
-        return unicode(value)
-
 class AutoField(Field):
     empty_strings_allowed = False
     def __init__(self, *args, **kwargs):
         defaults.update(kwargs)
         return super(DecimalField, self).formfield(**defaults)
 
-    def _localize_funct(self, value):
-        from django.utils.formats import number_format
-        return number_format(value)
-
 class EmailField(CharField):
     def __init__(self, *args, **kwargs):
         kwargs['max_length'] = kwargs.get('max_length', 75)

django/template/__init__.py

 from django.utils.encoding import smart_unicode, force_unicode, smart_str
 from django.utils.translation import ugettext as _
 from django.utils.safestring import SafeData, EscapeData, mark_safe, mark_for_escaping
+from django.utils.formats import localize
 from django.utils.html import escape
 
 __all__ = ('Template', 'Context', 'RequestContext', 'compile_string')
                     else:
                         raise
 
-        if hasattr(current, 'localize'):
-            return current.localize()
-        else:
-            return current
+        return current
 
 class Node(object):
     # Set this to True for nodes that must be first in the template (although
     means escaping, if required, and conversion to a unicode object. If value
     is a string, it is expected to have already been translated.
     """
+    value = localize(value)
     value = force_unicode(value)
     if (context.autoescape and not isinstance(value, SafeData)) or isinstance(value, EscapeData):
         return escape(value)

django/template/debug.py

 from django.utils.encoding import force_unicode
 from django.utils.html import escape
 from django.utils.safestring import SafeData, EscapeData
+from django.utils.formats import localize
 
 class DebugLexer(Lexer):
     def __init__(self, template_string, origin):
 class DebugVariableNode(VariableNode):
     def render(self, context):
         try:
-            output = force_unicode(self.filter_expression.resolve(context))
+            output = self.filter_expression.resolve(context)
+            output = localize(output)
+            output = force_unicode(output)
         except TemplateSyntaxError, e:
             if not hasattr(e, 'source'):
                 e.source = self.source

django/utils/formats.py

+import decimal
+import datetime
+
 from django.utils.importlib import import_module
+from django.utils import dateformat
+from django.utils import numberformat 
 
 def getformat_null(format_type):
     """
 else:
     getformat = getformat_null
 
-def date_and_time_format(value, format):
-    import dateformat
-    return dateformat.format(value, getformat('DATE_FORMAT'))
-
-def date_format(value):
-    import dateformat
-    return dateformat.format(value, getformat('DATE_FORMAT'))
-
-def datetime_format(value):
-    import dateformat
-    return dateformat.format(value, getformat('DATE_FORMAT'))
-
-def time_format(value):
-    import dateformat
-    return dateformat.time_format(value, getformat('TIME_FORMAT'))
+def date_format(value, format=None):
+    return dateformat.format(value, getformat(format or 'DATE_FORMAT'))
 
 def number_format(value):
-    import numberformat
     return numberformat.format(
         value,
         getformat('DECIMAL_SEPARATOR'),
         getformat('THOUSAND_SEPARATOR'),
     )
 
+def localize(value):
+    if settings.USE_I18N and settings.USE_FORMAT_I18N:
+        if isinstance(value, decimal.Decimal):
+            return number_format(value)
+        elif isinstance(value, datetime.datetime):
+            return date_format(value, 'DATETIME_FORMAT')
+        elif isinstance(value, datetime.date):
+            return date_format(value)
+    return value
+
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.