我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.forms.DecimalField()。
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)
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
def validators(self): return super(DecimalField, self).validators + [ validators.DecimalValidator(self.max_digits, self.decimal_places) ]
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
def get_internal_type(self): return "DecimalField"
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)
def __init__(self, *args, **kwargs): kwargs['required'] = False forms.DecimalField.__init__(self, *args, **kwargs)
def __init__(self, *args, **kwargs): import warnings warnings.warn( "class livesettings.PercentValue is deprecated. It should be replaced in config.py by " \ "DecimalValue(... min_value=0, max_value=100) and the result divided by 100 in the app.", DeprecationWarning ) kwargs['required'] = False forms.DecimalField.__init__(self, 100, 0, 5, 2, *args, **kwargs)
def clean(self, value): if value == '': value = 0 value = super(forms.DecimalField, self).clean(value) try: value = Decimal(value) except: raise forms.ValidationError('This value must be a decimal number.') return str(Decimal(value) / 100)
def __init__(self, *args, **kwargs): self.widget = GeopositionWidget() fields = ( forms.DecimalField(label=_('latitude')), forms.DecimalField(label=_('longitude')), ) if 'initial' in kwargs: kwargs['initial'] = Geoposition(*kwargs['initial'].split(',')) super(GeopositionField, self).__init__(fields, **kwargs)
def test_fields(self): """ This tests that all fields were added to the form with the correct types """ form_class = self.fb.get_form_class() field_names = form_class.base_fields.keys() # All fields are present in form self.assertIn('your-name', field_names) self.assertIn('your-biography', field_names) self.assertIn('your-birthday', field_names) self.assertIn('your-birthtime', field_names) self.assertIn('your-email', field_names) self.assertIn('your-homepage', field_names) self.assertIn('your-favourite-number', field_names) self.assertIn('your-favourite-python-ides', field_names) self.assertIn('your-favourite-python-ide', field_names) self.assertIn('your-choices', field_names) self.assertIn('i-agree-to-the-terms-of-use', field_names) # All fields have proper type self.assertIsInstance(form_class.base_fields['your-name'], forms.CharField) self.assertIsInstance(form_class.base_fields['your-biography'], forms.CharField) self.assertIsInstance(form_class.base_fields['your-birthday'], forms.DateField) self.assertIsInstance(form_class.base_fields['your-birthtime'], forms.DateTimeField) self.assertIsInstance(form_class.base_fields['your-email'], forms.EmailField) self.assertIsInstance(form_class.base_fields['your-homepage'], forms.URLField) self.assertIsInstance(form_class.base_fields['your-favourite-number'], forms.DecimalField) self.assertIsInstance(form_class.base_fields['your-favourite-python-ides'], forms.ChoiceField) self.assertIsInstance(form_class.base_fields['your-favourite-python-ide'], forms.ChoiceField) self.assertIsInstance(form_class.base_fields['your-choices'], forms.MultipleChoiceField) self.assertIsInstance(form_class.base_fields['i-agree-to-the-terms-of-use'], forms.BooleanField) # Some fields have non-default widgets self.assertIsInstance(form_class.base_fields['your-biography'].widget, forms.Textarea) self.assertIsInstance(form_class.base_fields['your-favourite-python-ide'].widget, forms.RadioSelect) self.assertIsInstance(form_class.base_fields['your-choices'].widget, forms.CheckboxSelectMultiple)
def __init__(self, max_value=None, min_value=None, max_digits=None, decimal_places=None, *args, **kwargs): self.max_value, self.min_value = max_value, min_value self.max_digits, self.decimal_places = max_digits, decimal_places super(DecimalField, self).__init__(*args, **kwargs) if max_value is not None: self.validators.append(validators.MaxValueValidator(max_value)) if min_value is not None: self.validators.append(validators.MinValueValidator(min_value))
def validate(self, value): super(DecimalField, self).validate(value) if value in validators.EMPTY_VALUES: return # Check for NaN, Inf and -Inf values. We can't compare directly for NaN, # since it is never equal to itself. However, NaN is the only value that # isn't equal to itself, so we can use this to identify NaN if value != value or value == Decimal("Inf") or value == Decimal("-Inf"): raise ValidationError(self.error_messages['invalid']) sign, digittuple, exponent = value.as_tuple() decimals = abs(exponent) # digittuple doesn't include any leading zeros. digits = len(digittuple) if decimals > digits: # We have leading zeros up to or past the decimal point. Count # everything past the decimal point as a digit. We do not count # 0 before the decimal point as a digit since that would mean # we would not allow max_digits = decimal_places. digits = decimals whole_digits = digits - decimals if self.max_digits is not None and digits > self.max_digits: raise ValidationError(self.error_messages['max_digits'] % self.max_digits) if self.decimal_places is not None and decimals > self.decimal_places: raise ValidationError(self.error_messages['max_decimal_places'] % self.decimal_places) if (self.max_digits is not None and self.decimal_places is not None and whole_digits > (self.max_digits - self.decimal_places)): raise ValidationError(self.error_messages['max_whole_digits'] % (self.max_digits - self.decimal_places)) return value
def test_should_decimal_convert_float(): assert_conversion(forms.DecimalField, graphene.Float)
def get_prep_value(self, value): value = super(DecimalField, self).get_prep_value(value) return self.to_python(value)
def get_field(self, *, question, initial, initial_object, readonly): if question.variant == QuestionVariant.BOOLEAN: # For some reason, django-bootstrap4 does not set the required attribute # itself. widget = forms.CheckboxInput(attrs={'required': 'required'}) if question.required else forms.CheckboxInput() initialbool = (initial == 'True') if initial else bool(question.default_answer) return forms.BooleanField( disabled=readonly, help_text=question.help_text, label=question.question, required=question.required, widget=widget, initial=initialbool ) elif question.variant == QuestionVariant.NUMBER: return forms.DecimalField( disabled=readonly, help_text=question.help_text, label=question.question, required=question.required, min_value=Decimal('0.00'), initial=initial ) elif question.variant == QuestionVariant.STRING: return forms.CharField( disabled=readonly, help_text=question.help_text, label=question.question, required=question.required, initial=initial ) elif question.variant == QuestionVariant.TEXT: return forms.CharField( label=question.question, required=question.required, widget=forms.Textarea, disabled=readonly, help_text=question.help_text, initial=initial ) elif question.variant == QuestionVariant.FILE: return forms.FileField( label=question.question, required=question.required, disabled=readonly, help_text=question.help_text, initial=initial ) elif question.variant == QuestionVariant.CHOICES: return forms.ModelChoiceField( queryset=question.options.all(), label=question.question, required=question.required, initial=initial_object.options.first() if initial_object else question.default_answer, disabled=readonly, help_text=question.help_text, ) elif question.variant == QuestionVariant.MULTIPLE: return forms.ModelMultipleChoiceField( queryset=question.options.all(), label=question.question, required=question.required, widget=forms.CheckboxSelectMultiple, initial=initial_object.options.all() if initial_object else question.default_answer, disabled=readonly, help_text=question.help_text, )