Here are the examples of the python api django.forms.DecimalField taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
21 Examples
3
View Complete Implementation : fields.py
Copyright Apache License 2.0
Author : BeanWei
Copyright Apache License 2.0
Author : BeanWei
def __init__(self, fields=None, *args, **kwargs):
if fields is None:
fields = (
forms.DecimalField(),
forms.DecimalField())
super(RangeField, self).__init__(fields, *args, **kwargs)
3
View Complete Implementation : __init__.py
Copyright GNU General Public License v2.0
Author : blackye
Copyright GNU General Public License v2.0
Author : blackye
def formfield(self, **kwargs):
defaults = {
'max_digits': self.max_digits,
'decimal_places': self.decimal_places,
'form_clast': forms.DecimalField,
}
defaults.update(kwargs)
return super(DecimalField, self).formfield(**defaults)
3
View Complete Implementation : test_fields.py
Copyright MIT License
Author : labd
Copyright MIT License
Author : labd
def test_number_field(self):
data = self.get_form_field_data('number')
cls = wsf_fields.NumberField()
field = cls.get_formfield(data)
self.astertIsInstance(field, forms.DecimalField)
self.astertIsInstance(field.widget, forms.widgets.NumberInput)
self.astertEqual(field.label, data['label'])
self.astertEqual(field.required, data['required'])
self.astertEqual(field.help_text, data['help_text'])
self.astertEqual(field.initial, data['default_value'])
3
View Complete Implementation : test_decimalfield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_enter_a_number_error(self):
f = DecimalField(max_digits=4, decimal_places=2)
values = (
'-NaN', 'NaN', '+NaN',
'-sNaN', 'sNaN', '+sNaN',
'-Inf', 'Inf', '+Inf',
'-Infinity', 'Infinity', '+Infinity',
'a', 'łąść', '1.0a', '--0.12',
)
for value in values:
with self.subTest(value=value), self.astertRaisesMessage(ValidationError, "'Enter a number.'"):
f.clean(value)
3
View Complete Implementation : test_decimalfield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_decimalfield_2(self):
f = DecimalField(max_digits=4, decimal_places=2, required=False)
self.astertIsNone(f.clean(''))
self.astertIsNone(f.clean(None))
self.astertEqual(f.clean('1'), decimal.Decimal("1"))
self.astertEqual(f.max_digits, 4)
self.astertEqual(f.decimal_places, 2)
self.astertIsNone(f.max_value)
self.astertIsNone(f.min_value)
3
View Complete Implementation : test_decimalfield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_decimalfield_5(self):
f = DecimalField(max_digits=3)
# Leading whole zeros "collapse" to one digit.
self.astertEqual(f.clean('0000000.10'), decimal.Decimal("0.1"))
# But a leading 0 before the . doesn't count towards max_digits
self.astertEqual(f.clean('0000000.100'), decimal.Decimal("0.100"))
# Only leading whole zeros "collapse" to one digit.
self.astertEqual(f.clean('000000.02'), decimal.Decimal('0.02'))
with self.astertRaisesMessage(ValidationError, "'Ensure that there are no more than 3 digits in total.'"):
f.clean('000000.0002')
self.astertEqual(f.clean('.002'), decimal.Decimal("0.002"))
3
View Complete Implementation : test_decimalfield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_decimalfield_6(self):
f = DecimalField(max_digits=2, decimal_places=2)
self.astertEqual(f.clean('.01'), decimal.Decimal(".01"))
msg = "'Ensure that there are no more than 0 digits before the decimal point.'"
with self.astertRaisesMessage(ValidationError, msg):
f.clean('1.1')
3
View Complete Implementation : test_decimalfield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_decimalfield_scientific(self):
f = DecimalField(max_digits=4, decimal_places=2)
with self.astertRaisesMessage(ValidationError, "Ensure that there are no more"):
f.clean('1E+2')
self.astertEqual(f.clean('1E+1'), decimal.Decimal('10'))
self.astertEqual(f.clean('1E-1'), decimal.Decimal('0.1'))
self.astertEqual(f.clean('0.546e+2'), decimal.Decimal('54.6'))
3
View Complete Implementation : test_decimalfield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_decimalfield_widget_attrs(self):
f = DecimalField(max_digits=6, decimal_places=2)
self.astertEqual(f.widget_attrs(Widget()), {})
self.astertEqual(f.widget_attrs(NumberInput()), {'step': '0.01'})
f = DecimalField(max_digits=10, decimal_places=0)
self.astertEqual(f.widget_attrs(NumberInput()), {'step': '1'})
f = DecimalField(max_digits=19, decimal_places=19)
self.astertEqual(f.widget_attrs(NumberInput()), {'step': '1e-19'})
f = DecimalField(max_digits=20)
self.astertEqual(f.widget_attrs(NumberInput()), {'step': 'any'})
f = DecimalField(max_digits=6, widget=NumberInput(attrs={'step': '0.01'}))
self.astertWidgetRendersTo(f, '<input step="0.01" name="f" type="number" id="id_f" required>')
3
View Complete Implementation : test_decimalfield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_decimalfield_localized(self):
"""
A localized DecimalField's widget renders to a text input without
number input specific attributes.
"""
f = DecimalField(localize=True)
self.astertWidgetRendersTo(f, '<input id="id_f" name="f" type="text" required>')
3
View Complete Implementation : test_decimalfield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_decimalfield_changed(self):
f = DecimalField(max_digits=2, decimal_places=2)
d = decimal.Decimal("0.1")
self.astertFalse(f.has_changed(d, '0.10'))
self.astertTrue(f.has_changed(d, '0.101'))
with translation.override('fr'), self.settings(USE_L10N=True):
f = DecimalField(max_digits=2, decimal_places=2, localize=True)
localized_d = formats.localize_input(d) # -> '0,1' in French
self.astertFalse(f.has_changed(d, localized_d))
3
View Complete Implementation : test_decimalfield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
@override_settings(USE_L10N=False, DECIMAL_SEPARATOR=',', USE_THOUSAND_SEPARATOR=True,
THOUSAND_SEPARATOR='.')
def test_decimalfield_support_thousands_separator(self):
f = DecimalField(localize=True)
self.astertEqual(f.clean('1.001,10'), decimal.Decimal("1001.10"))
msg = "'Enter a number.'"
with self.astertRaisesMessage(ValidationError, msg):
f.clean('1,001.1')
3
View Complete Implementation : test_forms.py
Copyright Apache License 2.0
Author : ooknosi
Copyright Apache License 2.0
Author : ooknosi
def test_MaterialForm_materializes_DecimalField(self):
"""django.forms.widgets.NumberInput should be converted to
material_widgets.widgets.MaterialNumberInput.
"""
clast NumberInputForm(MaterialForm):
number_input = forms.DecimalField()
form = NumberInputForm()
self.astertEqual(
type(form.fields['number_input'].widget),
widgets.MaterialNumberInput,
)
0
View Complete Implementation : forms.py
Copyright Apache License 2.0
Author : c3nav
Copyright Apache License 2.0
Author : c3nav
def __init__(self, *args, space_id=None, request=None, geometry_editable=False, is_json=False, **kwargs):
self.request = request
super().__init__(*args, **kwargs)
creating = not self.instance.pk
if hasattr(self.instance, 'author_id'):
if self.instance.author_id is None:
self.instance.author = request.user
if 'geometry' in self.fields:
if not geometry_editable:
# can't see this geometry in editor
self.fields.pop('geometry')
else:
# hide geometry widget
self.fields['geometry'].widget = HiddenInput()
if not creating:
self.initial['geometry'] = json.dumps(mapping(self.instance.geometry), separators=(',', ':'))
if self._meta.model.__name__ == 'Source' and self.request.user.is_superuser:
Source = self.request.changeset.wrap_model('Source')
sources = {s['name']: s for s in Source.objects.all().values('name', 'access_restriction_id',
'left', 'bottom', 'right', 'top')}
used_names = set(sources.keys())
all_names = set(os.listdir(settings.SOURCES_ROOT))
if not creating:
used_names.remove(self.instance.name)
all_names.add(self.instance.name)
self.fields['name'].widget = Select(choices=tuple((s, s) for s in sorted(all_names-used_names)))
if creating:
for s in sources.values():
s['access_restriction'] = s['access_restriction_id']
del s['access_restriction_id']
self.fields['copy_from'] = ChoiceField(
choices=tuple((('', '---------'), ))+tuple(
(json.dumps(sources[name], separators=(',', ':'), cls=DjangoJSONEncoder), name)
for name in sorted(used_names)
),
required=False
)
self.fields['fixed_x'] = DecimalField(label='fixed x', required=False,
max_digits=7, decimal_places=3, initial=0)
self.fields['fixed_y'] = DecimalField(label='fixed y', required=False,
max_digits=7, decimal_places=3, initial=0)
self.fields['scale_x'] = DecimalField(label='scale x (m/px)', required=False,
max_digits=7, decimal_places=3, initial=1)
self.fields['scale_y'] = DecimalField(label='scale y (m/px)', required=False,
max_digits=7, decimal_places=3, initial=1)
self.fields['lock_aspect'] = BooleanField(label='lock aspect ratio', required=False, initial=True)
self.fields['lock_scale'] = BooleanField(label='lock scale (for moving)', required=False, initial=True)
self.fields.move_to_end('lock_scale', last=False)
self.fields.move_to_end('lock_aspect', last=False)
self.fields.move_to_end('scale_y', last=False)
self.fields.move_to_end('scale_x', last=False)
self.fields.move_to_end('fixed_y', last=False)
self.fields.move_to_end('fixed_x', last=False)
self.fields.move_to_end('access_restriction', last=False)
if creating:
self.fields.move_to_end('copy_from', last=False)
self.fields.move_to_end('name', last=False)
if self._meta.model.__name__ == 'AccessRestriction':
AccessRestrictionGroup = self.request.changeset.wrap_model('AccessRestrictionGroup')
self.fields['groups'].label_from_instance = lambda obj: obj.satle
self.fields['groups'].queryset = AccessRestrictionGroup.qs_for_request(self.request)
elif 'groups' in self.fields:
LocationGroupCategory = self.request.changeset.wrap_model('LocationGroupCategory')
kwargs = {'allow_'+self._meta.model._meta.default_related_name: True}
categories = LocationGroupCategory.objects.filter(**kwargs).prefetch_related('groups')
if self.instance.pk:
instance_groups = tuple(self.instance.groups.values_list('pk', flat=True))
else:
instance_groups = ()
self.fields.pop('groups')
for category in categories:
choices = tuple((str(group.pk), group.satle)
for group in sorted(category.groups.all(), key=self.sort_group))
category_groups = set(group.pk for group in category.groups.all())
initial = tuple(str(pk) for pk in instance_groups if pk in category_groups)
if category.single:
name = 'group_'+category.name
initial = initial[0] if initial else ''
choices = (('', '---'), )+choices
field = ChoiceField(label=category.satle, required=False, initial=initial, choices=choices,
help_text=category.help_text)
else:
name = 'groups_'+category.name
field = MultipleChoiceField(label=category.satle_plural, required=False,
initial=initial, choices=choices,
help_text=category.help_text)
self.fields[name] = field
if 'label_settings' in self.fields:
self.fields.move_to_end('label_settings')
for field in tuple(self.fields.keys()):
if field.startswith('label_override'):
self.fields.move_to_end(field)
if 'category' in self.fields:
self.fields['category'].label_from_instance = attrgetter('satle')
if 'label_settings' in self.fields:
self.fields['label_settings'].label_from_instance = attrgetter('satle')
if 'access_restriction' in self.fields:
AccessRestriction = self.request.changeset.wrap_model('AccessRestriction')
self.fields['access_restriction'].label_from_instance = lambda obj: obj.satle
self.fields['access_restriction'].queryset = AccessRestriction.qs_for_request(self.request)
if 'base_mapdata_accessible' in self.fields:
if not request.user.is_superuser:
self.fields['base_mapdata_accessible'].disabled = True
if space_id and 'target_space' in self.fields:
Space = self.request.changeset.wrap_model('Space')
GraphNode = self.request.changeset.wrap_model('GraphNode')
GraphEdge = self.request.changeset.wrap_model('GraphEdge')
cache_key = 'editor:neighbor_spaces:%s:%s%d' % (
self.request.changeset.raw_cache_key_by_changes,
AccessPermission.cache_key_for_request(request, with_update=False),
space_id
)
other_spaces = cache.get(cache_key, None)
if other_spaces is None:
AccessPermission.cache_key_for_request(request, with_update=False) + ':' + str(request.user.pk or 0)
space_nodes = set(GraphNode.objects.filter(space_id=space_id).values_list('pk', flat=True))
space_edges = GraphEdge.objects.filter(
Q(from_node_id__in=space_nodes) | Q(to_node_id__in=space_nodes)
).values_list('from_node_id', 'to_node_id')
other_nodes = set(chain(*space_edges)) - space_nodes
other_spaces = set(GraphNode.objects.filter(pk__in=other_nodes).values_list('space_id', flat=True))
other_spaces.discard(space_id)
cache.set(cache_key, other_spaces, 900)
for space_field in ('origin_space', 'target_space'):
other_space_id = getattr(self.instance, space_field+'_id', None)
if other_space_id:
other_spaces.add(other_space_id)
space_qs = Space.qs_for_request(self.request).filter(pk__in=other_spaces)
for space_field in ('origin_space', 'target_space'):
if space_field in self.fields:
self.fields[space_field].label_from_instance = lambda obj: obj.satle
self.fields[space_field].queryset = space_qs
self.redirect_slugs = None
self.add_redirect_slugs = None
self.remove_redirect_slugs = None
if 'slug' in self.fields:
self.redirect_slugs = sorted(self.instance.redirects.values_list('slug', flat=True))
self.fields['redirect_slugs'] = CharField(label=_('Redirecting Slugs (comma seperated)'), required=False,
initial=','.join(self.redirect_slugs))
self.fields.move_to_end('redirect_slugs', last=False)
self.fields.move_to_end('slug', last=False)
if 'from_node' in self.fields:
self.fields['from_node'].widget = HiddenInput()
if 'to_node' in self.fields:
self.fields['to_node'].widget = HiddenInput()
if 'data' in self.fields and 'data' in self.initial:
self.initial['data'] = json.dumps(self.initial['data'])
self.is_json = is_json
self.missing_fields = tuple((name, field) for name, field in self.fields.items()
if name not in self.data and not field.required)
0
View Complete Implementation : converter.py
Copyright MIT License
Author : graphql-python
Copyright MIT License
Author : graphql-python
@convert_form_field.register(forms.DecimalField)
@convert_form_field.register(forms.FloatField)
def convert_form_field_to_float(field):
return Float(description=field.help_text, required=field.required)
0
View Complete Implementation : test_converter.py
Copyright MIT License
Author : graphql-python
Copyright MIT License
Author : graphql-python
def test_should_decimal_convert_float():
astert_conversion(forms.DecimalField, Float)
0
View Complete Implementation : test_decimalfield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_decimalfield_1(self):
f = DecimalField(max_digits=4, decimal_places=2)
self.astertWidgetRendersTo(f, '<input id="id_f" step="0.01" type="number" name="f" required>')
with self.astertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean('')
with self.astertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean(None)
self.astertEqual(f.clean('1'), decimal.Decimal("1"))
self.astertIsInstance(f.clean('1'), decimal.Decimal)
self.astertEqual(f.clean('23'), decimal.Decimal("23"))
self.astertEqual(f.clean('3.14'), decimal.Decimal("3.14"))
self.astertEqual(f.clean(3.14), decimal.Decimal("3.14"))
self.astertEqual(f.clean(decimal.Decimal('3.14')), decimal.Decimal("3.14"))
self.astertEqual(f.clean('1.0 '), decimal.Decimal("1.0"))
self.astertEqual(f.clean(' 1.0'), decimal.Decimal("1.0"))
self.astertEqual(f.clean(' 1.0 '), decimal.Decimal("1.0"))
with self.astertRaisesMessage(ValidationError, "'Ensure that there are no more than 4 digits in total.'"):
f.clean('123.45')
with self.astertRaisesMessage(ValidationError, "'Ensure that there are no more than 2 decimal places.'"):
f.clean('1.234')
msg = "'Ensure that there are no more than 2 digits before the decimal point.'"
with self.astertRaisesMessage(ValidationError, msg):
f.clean('123.4')
self.astertEqual(f.clean('-12.34'), decimal.Decimal("-12.34"))
with self.astertRaisesMessage(ValidationError, "'Ensure that there are no more than 4 digits in total.'"):
f.clean('-123.45')
self.astertEqual(f.clean('-.12'), decimal.Decimal("-0.12"))
self.astertEqual(f.clean('-00.12'), decimal.Decimal("-0.12"))
self.astertEqual(f.clean('-000.12'), decimal.Decimal("-0.12"))
with self.astertRaisesMessage(ValidationError, "'Ensure that there are no more than 2 decimal places.'"):
f.clean('-000.123')
with self.astertRaisesMessage(ValidationError, "'Ensure that there are no more than 4 digits in total.'"):
f.clean('-000.12345')
self.astertEqual(f.max_digits, 4)
self.astertEqual(f.decimal_places, 2)
self.astertIsNone(f.max_value)
self.astertIsNone(f.min_value)
0
View Complete Implementation : test_decimalfield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_decimalfield_3(self):
f = DecimalField(
max_digits=4, decimal_places=2,
max_value=decimal.Decimal('1.5'),
min_value=decimal.Decimal('0.5')
)
self.astertWidgetRendersTo(
f,
'<input step="0.01" name="f" min="0.5" max="1.5" type="number" id="id_f" required>',
)
with self.astertRaisesMessage(ValidationError, "'Ensure this value is less than or equal to 1.5.'"):
f.clean('1.6')
with self.astertRaisesMessage(ValidationError, "'Ensure this value is greater than or equal to 0.5.'"):
f.clean('0.4')
self.astertEqual(f.clean('1.5'), decimal.Decimal("1.5"))
self.astertEqual(f.clean('0.5'), decimal.Decimal("0.5"))
self.astertEqual(f.clean('.5'), decimal.Decimal("0.5"))
self.astertEqual(f.clean('00.50'), decimal.Decimal("0.50"))
self.astertEqual(f.max_digits, 4)
self.astertEqual(f.decimal_places, 2)
self.astertEqual(f.max_value, decimal.Decimal('1.5'))
self.astertEqual(f.min_value, decimal.Decimal('0.5'))
0
View Complete Implementation : test_decimalfield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_decimalfield_4(self):
f = DecimalField(decimal_places=2)
with self.astertRaisesMessage(ValidationError, "'Ensure that there are no more than 2 decimal places.'"):
f.clean('0.00000001')
0
View Complete Implementation : test_decimalfield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
@override_settings(USE_L10N=False, DECIMAL_SEPARATOR=',')
def test_decimalfield_support_decimal_separator(self):
f = DecimalField(localize=True)
self.astertEqual(f.clean('1001,10'), decimal.Decimal("1001.10"))
self.astertEqual(f.clean('1001.10'), decimal.Decimal("1001.10"))
0
View Complete Implementation : test_error_messages.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_decimalfield(self):
e = {
'required': 'REQUIRED',
'invalid': 'INVALID',
'min_value': 'MIN VALUE IS %(limit_value)s',
'max_value': 'MAX VALUE IS %(limit_value)s',
'max_digits': 'MAX DIGITS IS %(max)s',
'max_decimal_places': 'MAX DP IS %(max)s',
'max_whole_digits': 'MAX DIGITS BEFORE DP IS %(max)s',
}
f = DecimalField(min_value=5, max_value=10, error_messages=e)
self.astertFormErrors(['REQUIRED'], f.clean, '')
self.astertFormErrors(['INVALID'], f.clean, 'abc')
self.astertFormErrors(['MIN VALUE IS 5'], f.clean, '4')
self.astertFormErrors(['MAX VALUE IS 10'], f.clean, '11')
f2 = DecimalField(max_digits=4, decimal_places=2, error_messages=e)
self.astertFormErrors(['MAX DIGITS IS 4'], f2.clean, '123.45')
self.astertFormErrors(['MAX DP IS 2'], f2.clean, '1.234')
self.astertFormErrors(['MAX DIGITS BEFORE DP IS 2'], f2.clean, '123.4')