Code

Ticket #13032: 13032.1.diff

File 13032.1.diff, 7.2 KB (added by jezdez, 4 years ago)

Added localize parameter to form fields to be able to selectively enable localization

Line 
1diff --git a/django/forms/fields.py b/django/forms/fields.py
2index b31fe80..0ad5f93 100644
3--- a/django/forms/fields.py
4+++ b/django/forms/fields.py
5@@ -71,7 +71,7 @@ class Field(object):
6 
7     def __init__(self, required=True, widget=None, label=None, initial=None,
8                  help_text=None, error_messages=None, show_hidden_initial=False,
9-                 validators=[]):
10+                 validators=[], localize=False):
11         # required -- Boolean that specifies whether the field is required.
12         #             True by default.
13         # widget -- A Widget class, or instance of a Widget class, that should
14@@ -85,9 +85,12 @@ class Field(object):
15         # initial -- A value to use in this Field's initial display. This value
16         #            is *not* used as a fallback if data isn't given.
17         # help_text -- An optional string to use as "help text" for this Field.
18+        # error_messages -- An optional dictionary to override the default
19+        #                   messages that the field will raise.
20         # show_hidden_initial -- Boolean that specifies if it is needed to render a
21         #                        hidden widget with initial value after widget.
22         # validators -- List of addtional validators to use
23+        # localize -- Boolean that specifies if the field should be localized.
24         if label is not None:
25             label = smart_unicode(label)
26         self.required, self.label, self.initial = required, label, initial
27@@ -100,6 +103,11 @@ class Field(object):
28         if isinstance(widget, type):
29             widget = widget()
30 
31+        # Trigger the localization machinery if needed.
32+        if localize:
33+            widget.is_localized = True
34+        self.localize = localize
35+
36         # Hook into self.widget_attrs() for any Field-specific HTML attributes.
37         extra_attrs = self.widget_attrs(widget)
38         if extra_attrs:
39@@ -213,7 +221,8 @@ class IntegerField(Field):
40         value = super(IntegerField, self).to_python(value)
41         if value in validators.EMPTY_VALUES:
42             return None
43-        value = formats.sanitize_separators(value)
44+        if self.localize:
45+            value = formats.sanitize_separators(value)
46         try:
47             value = int(str(value))
48         except (ValueError, TypeError):
49@@ -233,7 +242,8 @@ class FloatField(IntegerField):
50         value = super(IntegerField, self).to_python(value)
51         if value in validators.EMPTY_VALUES:
52             return None
53-        value = formats.sanitize_separators(value)
54+        if self.localize:
55+            value = formats.sanitize_separators(value)
56         try:
57             value = float(value)
58         except (ValueError, TypeError):
59@@ -268,7 +278,8 @@ class DecimalField(Field):
60         """
61         if value in validators.EMPTY_VALUES:
62             return None
63-        value = formats.sanitize_separators(value)
64+        if self.localize:
65+            value = formats.sanitize_separators(value)
66         value = smart_str(value).strip()
67         try:
68             value = Decimal(value)
69diff --git a/django/forms/widgets.py b/django/forms/widgets.py
70index 8b4112b..99c19d8 100644
71--- a/django/forms/widgets.py
72+++ b/django/forms/widgets.py
73@@ -134,6 +134,7 @@ class Widget(object):
74     __metaclass__ = MediaDefiningClass
75     is_hidden = False          # Determines whether this corresponds to an <input type="hidden">.
76     needs_multipart_form = False # Determines does this widget need multipart-encrypted form
77+    is_localized = False
78 
79     def __init__(self, attrs=None):
80         if attrs is not None:
81@@ -214,7 +215,9 @@ class Input(Widget):
82         final_attrs = self.build_attrs(attrs, type=self.input_type, name=name)
83         if value != '':
84             # Only add the 'value' attribute if a value is non-empty.
85-            final_attrs['value'] = force_unicode(formats.localize_input(value))
86+            if self.is_localized:
87+                value = formats.localize_input(value)
88+            final_attrs['value'] = force_unicode(value)
89         return mark_safe(u'<input%s />' % flatatt(final_attrs))
90 
91 class TextInput(Input):
92@@ -675,6 +678,9 @@ class MultiWidget(Widget):
93         super(MultiWidget, self).__init__(attrs)
94 
95     def render(self, name, value, attrs=None):
96+        if self.is_localized:
97+            for widget in self.widgets:
98+                widget.is_localized = self.is_localized
99         # value is a list of values, each corresponding to a widget
100         # in self.widgets.
101         if not isinstance(value, list):
102diff --git a/tests/regressiontests/forms/widgets.py b/tests/regressiontests/forms/widgets.py
103index cc83a88..7a12c7b 100644
104--- a/tests/regressiontests/forms/widgets.py
105+++ b/tests/regressiontests/forms/widgets.py
106@@ -1261,6 +1261,7 @@ u'<input type="hidden" name="date_0" value="2007-09-17" /><input type="hidden" n
107 >>> w.render('date', datetime.datetime(2007, 9, 17, 12, 51))
108 u'<input type="hidden" name="date_0" value="2007-09-17" /><input type="hidden" name="date_1" value="12:51:00" />'
109 >>> activate('de-at')
110+>>> w.is_localized = True
111 >>> settings.USE_L10N = True
112 >>> w.render('date', datetime.datetime(2007, 9, 17, 12, 51))
113 u'<input type="hidden" name="date_0" value="17.09.2007" /><input type="hidden" name="date_1" value="12:51:00" />'
114diff --git a/tests/regressiontests/i18n/forms.py b/tests/regressiontests/i18n/forms.py
115index 8ed834c..216d1fe 100644
116--- a/tests/regressiontests/i18n/forms.py
117+++ b/tests/regressiontests/i18n/forms.py
118@@ -3,16 +3,19 @@ from django.forms.extras import SelectDateWidget
119 from models import Company
120 
121 class I18nForm(forms.Form):
122-    decimal_field = forms.DecimalField()
123-    float_field = forms.FloatField()
124-    date_field = forms.DateField()
125-    datetime_field = forms.DateTimeField()
126-    time_field = forms.TimeField()
127-    integer_field = forms.IntegerField()
128+    decimal_field = forms.DecimalField(localize=True)
129+    float_field = forms.FloatField(localize=True)
130+    date_field = forms.DateField(localize=True)
131+    datetime_field = forms.DateTimeField(localize=True)
132+    time_field = forms.TimeField(localize=True)
133+    integer_field = forms.IntegerField(localize=True)
134 
135 class SelectDateForm(forms.Form):
136     date_field = forms.DateField(widget=SelectDateWidget)
137 
138 class CompanyForm(forms.ModelForm):
139+    cents_payed = forms.DecimalField(max_digits=4, decimal_places=2, localize=True)
140+    products_delivered = forms.IntegerField(localize=True)
141+
142     class Meta:
143         model = Company
144diff --git a/tests/regressiontests/i18n/tests.py b/tests/regressiontests/i18n/tests.py
145index 31150a6..9cc1089 100644
146--- a/tests/regressiontests/i18n/tests.py
147+++ b/tests/regressiontests/i18n/tests.py
148@@ -410,7 +410,8 @@ class FormattingTests(TestCase):
149             self.assertEqual(localize_input(datetime.datetime(2009, 12, 31, 6, 0, 0)), '31.12.2009 06:00:00')
150             self.assertEqual(datetime.datetime(2009, 12, 31, 6, 0, 0), form6.cleaned_data['date_added'])
151             settings.USE_THOUSAND_SEPARATOR = True
152-            self.assert_(u'12.000' in form6.as_ul())
153+            # Checking for the localized "products_delivered" field
154+            self.assert_(u'<input type="text" name="products_delivered" value="12.000" id="id_products_delivered" />' in form6.as_ul())
155         finally:
156             deactivate()
157