Python django.forms.DecimalField() Examples

The following are 30 code examples for showing how to use django.forms.DecimalField(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.forms , or try the search function .

Example 1
Project: byro   Author: byro   File: registration.py    License: Apache License 2.0 6 votes vote down vote up
def build_default_field(self, field, model):
        choices = getattr(field, "choices", None)
        if choices:
            return forms.ChoiceField(
                required=False,
                label=_("Default value"),
                choices=[(None, "-----------")] + list(choices),
            )
        if not (model is Member and field.name == "number"):
            if isinstance(field, models.CharField):
                return forms.CharField(required=False, label=_("Default value"))
            elif isinstance(field, models.DecimalField):
                return forms.DecimalField(
                    required=False,
                    label=_("Default value"),
                    max_digits=field.max_digits,
                    decimal_places=field.decimal_places,
                )
            elif isinstance(field, models.DateField):
                return forms.CharField(required=False, label=_("Other/fixed date")) 
Example 2
Project: mrs   Author: betagouv   File: forms.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def to_python(self, value):

        comma_index = 0

        if value:

            # First we check if there is a comma inside the decimal input, and
            # store its position
            try:
                comma_index = value.index(',')
            except ValueError:
                pass

            # If we found a comma inside the input value, we replace it with a
            # regular dot
            if comma_index:
                value = value.replace(',', '.')

        # We finally pass the value (modified or not) to the standard
        # DecimalField
        return super(AllowedCommaDecimalField, self).to_python(value) 
Example 3
Project: djongo   Author: nesdis   File: test_decimalfield.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
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.assertWidgetRendersTo(
            f,
            '<input step="0.01" name="f" min="0.5" max="1.5" type="number" id="id_f" required>',
        )
        with self.assertRaisesMessage(ValidationError, "'Ensure this value is less than or equal to 1.5.'"):
            f.clean('1.6')
        with self.assertRaisesMessage(ValidationError, "'Ensure this value is greater than or equal to 0.5.'"):
            f.clean('0.4')
        self.assertEqual(f.clean('1.5'), decimal.Decimal("1.5"))
        self.assertEqual(f.clean('0.5'), decimal.Decimal("0.5"))
        self.assertEqual(f.clean('.5'), decimal.Decimal("0.5"))
        self.assertEqual(f.clean('00.50'), decimal.Decimal("0.50"))
        self.assertEqual(f.max_digits, 4)
        self.assertEqual(f.decimal_places, 2)
        self.assertEqual(f.max_value, decimal.Decimal('1.5'))
        self.assertEqual(f.min_value, decimal.Decimal('0.5')) 
Example 4
Project: djongo   Author: nesdis   File: test_decimalfield.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
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.assertWidgetRendersTo(
            f,
            '<input step="0.01" name="f" min="0.5" max="1.5" type="number" id="id_f" required>',
        )
        with self.assertRaisesMessage(ValidationError, "'Ensure this value is less than or equal to 1.5.'"):
            f.clean('1.6')
        with self.assertRaisesMessage(ValidationError, "'Ensure this value is greater than or equal to 0.5.'"):
            f.clean('0.4')
        self.assertEqual(f.clean('1.5'), decimal.Decimal("1.5"))
        self.assertEqual(f.clean('0.5'), decimal.Decimal("0.5"))
        self.assertEqual(f.clean('.5'), decimal.Decimal("0.5"))
        self.assertEqual(f.clean('00.50'), decimal.Decimal("0.50"))
        self.assertEqual(f.max_digits, 4)
        self.assertEqual(f.decimal_places, 2)
        self.assertEqual(f.max_value, decimal.Decimal('1.5'))
        self.assertEqual(f.min_value, decimal.Decimal('0.5')) 
Example 5
Project: django-places   Author: oscarmcm   File: forms.py    License: MIT License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        fields = (
            forms.CharField(label=_('place')),
            forms.DecimalField(label=_('Latitude')),
            forms.DecimalField(label=_('Longitude')),
        )
        if 'initial' in kwargs:
            kwargs['initial'] = Places(*kwargs['initial'].split(','))
        self.widget = PlacesWidget()
        super(PlacesField, self).__init__(fields, **kwargs) 
Example 6
Project: donation-tracker   Author: GamesDoneQuick   File: forms.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, event=None, *args, **kwargs):
        super(DonationEntryForm, self).__init__(*args, **kwargs)
        minDonationAmount = (
            event.minimumdonation if event is not None else Decimal('1.00')
        )
        self.fields['amount'] = forms.DecimalField(
            decimal_places=2,
            min_value=minDonationAmount,
            max_value=Decimal('100000'),
            label='Donation Amount (min ${0})'.format(minDonationAmount),
            widget=tracker.widgets.NumberInput(
                attrs={
                    'id': 'iDonationAmount',
                    'min': str(minDonationAmount),
                    'step': '0.01',
                }
            ),
            required=True,
        )
        self.fields['comment'] = forms.CharField(widget=forms.Textarea, required=False)
        self.fields['requestedvisibility'] = forms.ChoiceField(
            initial='CURR',
            choices=models.Donation._meta.get_field('requestedvisibility').choices,
            label='Name Visibility',
        )
        self.fields['requestedalias'] = forms.CharField(
            max_length=32, label='Preferred Alias', required=False
        )
        self.fields['requestedemail'] = forms.EmailField(
            max_length=128, label='Preferred Email', required=False
        )
        self.fields['requestedsolicitemail'] = forms.ChoiceField(
            initial='CURR',
            choices=models.Donation._meta.get_field('requestedsolicitemail').choices,
            label='Charity Email Opt In',
        ) 
Example 7
Project: coursys   Author: sfu-fas   File: mc.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, n=10, required=True, *args, **kwargs):
        self.n = n
        self.require_one = required
        fields = [
            forms.CharField(required=False, max_length=1000, initial='')
            for _ in range(self.n)
        ]
        fields += [
            forms.DecimalField(required=False, initial=0)
            for _ in range(self.n)
        ]
        super().__init__(fields=fields, require_all_fields=False, required=False, *args, **kwargs)
        self.force_display_required = True 
Example 8
Project: GTDWeb   Author: lanbing510   File: __init__.py    License: GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, verbose_name=None, name=None, max_digits=None,
                 decimal_places=None, **kwargs):
        self.max_digits, self.decimal_places = max_digits, decimal_places
        super(DecimalField, self).__init__(verbose_name, name, **kwargs) 
Example 9
Project: GTDWeb   Author: lanbing510   File: __init__.py    License: GNU General Public License v2.0 5 votes vote down vote up
def check(self, **kwargs):
        errors = super(DecimalField, self).check(**kwargs)

        digits_errors = self._check_decimal_places()
        digits_errors.extend(self._check_max_digits())
        if not digits_errors:
            errors.extend(self._check_decimal_places_and_max_digits(**kwargs))
        else:
            errors.extend(digits_errors)
        return errors 
Example 10
Project: GTDWeb   Author: lanbing510   File: __init__.py    License: GNU General Public License v2.0 5 votes vote down vote up
def deconstruct(self):
        name, path, args, kwargs = super(DecimalField, self).deconstruct()
        if self.max_digits is not None:
            kwargs['max_digits'] = self.max_digits
        if self.decimal_places is not None:
            kwargs['decimal_places'] = self.decimal_places
        return name, path, args, kwargs 
Example 11
Project: GTDWeb   Author: lanbing510   File: __init__.py    License: GNU General Public License v2.0 5 votes vote down vote up
def get_internal_type(self):
        return "DecimalField" 
Example 12
Project: GTDWeb   Author: lanbing510   File: __init__.py    License: GNU General Public License v2.0 5 votes vote down vote up
def get_prep_value(self, value):
        value = super(DecimalField, self).get_prep_value(value)
        return self.to_python(value) 
Example 13
Project: bioforum   Author: reBiocoder   File: __init__.py    License: MIT License 5 votes vote down vote up
def get_internal_type(self):
        return "DecimalField" 
Example 14
Project: bioforum   Author: reBiocoder   File: __init__.py    License: MIT License 5 votes vote down vote up
def formfield(self, **kwargs):
        defaults = {
            'max_digits': self.max_digits,
            'decimal_places': self.decimal_places,
            'form_class': forms.DecimalField,
        }
        defaults.update(kwargs)
        return super().formfield(**defaults) 
Example 15
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: __init__.py    License: MIT License 5 votes vote down vote up
def get_internal_type(self):
        return "DecimalField" 
Example 16
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: __init__.py    License: MIT License 5 votes vote down vote up
def formfield(self, **kwargs):
        return super().formfield(**{
            'max_digits': self.max_digits,
            'decimal_places': self.decimal_places,
            'form_class': forms.DecimalField,
            **kwargs,
        }) 
Example 17
Project: wagtail   Author: wagtail   File: field_block.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, required=True, help_text=None, max_value=None, min_value=None,
                 max_digits=None, decimal_places=None, validators=(), *args, **kwargs):
        self.field = forms.DecimalField(
            required=required,
            help_text=help_text,
            max_value=max_value,
            min_value=min_value,
            max_digits=max_digits,
            decimal_places=decimal_places,
            validators=validators,
        )
        super().__init__(*args, **kwargs) 
Example 18
Project: wagtailstreamforms   Author: labd   File: test_fields.py    License: MIT License 5 votes vote down vote up
def test_number_field(self):
        data = self.get_form_field_data("number")
        cls = wsf_fields.NumberField()
        field = cls.get_formfield(data)

        self.assertIsInstance(field, forms.DecimalField)
        self.assertIsInstance(field.widget, forms.widgets.NumberInput)
        self.assertEqual(field.label, data["label"])
        self.assertEqual(field.required, data["required"])
        self.assertEqual(field.help_text, data["help_text"])
        self.assertEqual(field.initial, data["default_value"]) 
Example 19
Project: python   Author: Yeah-Kun   File: __init__.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, verbose_name=None, name=None, max_digits=None,
                 decimal_places=None, **kwargs):
        self.max_digits, self.decimal_places = max_digits, decimal_places
        super(DecimalField, self).__init__(verbose_name, name, **kwargs) 
Example 20
Project: python   Author: Yeah-Kun   File: __init__.py    License: Apache License 2.0 5 votes vote down vote up
def check(self, **kwargs):
        errors = super(DecimalField, self).check(**kwargs)

        digits_errors = self._check_decimal_places()
        digits_errors.extend(self._check_max_digits())
        if not digits_errors:
            errors.extend(self._check_decimal_places_and_max_digits(**kwargs))
        else:
            errors.extend(digits_errors)
        return errors 
Example 21
Project: python   Author: Yeah-Kun   File: __init__.py    License: Apache License 2.0 5 votes vote down vote up
def validators(self):
        return super(DecimalField, self).validators + [
            validators.DecimalValidator(self.max_digits, self.decimal_places)
        ] 
Example 22
Project: python   Author: Yeah-Kun   File: __init__.py    License: Apache License 2.0 5 votes vote down vote up
def deconstruct(self):
        name, path, args, kwargs = super(DecimalField, self).deconstruct()
        if self.max_digits is not None:
            kwargs['max_digits'] = self.max_digits
        if self.decimal_places is not None:
            kwargs['decimal_places'] = self.decimal_places
        return name, path, args, kwargs 
Example 23
Project: python   Author: Yeah-Kun   File: __init__.py    License: Apache License 2.0 5 votes vote down vote up
def get_internal_type(self):
        return "DecimalField" 
Example 24
Project: python   Author: Yeah-Kun   File: __init__.py    License: Apache License 2.0 5 votes vote down vote up
def formfield(self, **kwargs):
        defaults = {
            'max_digits': self.max_digits,
            'decimal_places': self.decimal_places,
            'form_class': forms.DecimalField,
        }
        defaults.update(kwargs)
        return super(DecimalField, self).formfield(**defaults) 
Example 25
Project: luscan-devel   Author: blackye   File: __init__.py    License: GNU General Public License v2.0 5 votes vote down vote up
def get_internal_type(self):
        return "DecimalField" 
Example 26
Project: luscan-devel   Author: blackye   File: __init__.py    License: GNU General Public License v2.0 5 votes vote down vote up
def formfield(self, **kwargs):
        defaults = {
            'max_digits': self.max_digits,
            'decimal_places': self.decimal_places,
            'form_class': forms.DecimalField,
        }
        defaults.update(kwargs)
        return super(DecimalField, self).formfield(**defaults) 
Example 27
Project: openhgsenti   Author: drexly   File: __init__.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, verbose_name=None, name=None, max_digits=None,
                 decimal_places=None, **kwargs):
        self.max_digits, self.decimal_places = max_digits, decimal_places
        super(DecimalField, self).__init__(verbose_name, name, **kwargs) 
Example 28
Project: openhgsenti   Author: drexly   File: __init__.py    License: Apache License 2.0 5 votes vote down vote up
def check(self, **kwargs):
        errors = super(DecimalField, self).check(**kwargs)

        digits_errors = self._check_decimal_places()
        digits_errors.extend(self._check_max_digits())
        if not digits_errors:
            errors.extend(self._check_decimal_places_and_max_digits(**kwargs))
        else:
            errors.extend(digits_errors)
        return errors 
Example 29
Project: openhgsenti   Author: drexly   File: __init__.py    License: Apache License 2.0 5 votes vote down vote up
def validators(self):
        return super(DecimalField, self).validators + [
            validators.DecimalValidator(self.max_digits, self.decimal_places)
        ] 
Example 30
Project: openhgsenti   Author: drexly   File: __init__.py    License: Apache License 2.0 5 votes vote down vote up
def deconstruct(self):
        name, path, args, kwargs = super(DecimalField, self).deconstruct()
        if self.max_digits is not None:
            kwargs['max_digits'] = self.max_digits
        if self.decimal_places is not None:
            kwargs['decimal_places'] = self.decimal_places
        return name, path, args, kwargs