Django: FloatField for newforms
I'm trying to develop something using Django because it must be cross-platform. The easiest solution for cross-platform application is web-based application. Since I have just started and the document recommends me to use newforms instead of the oldforms. The concept of newforms is to define fields in the form for later validation and rendering the form in various formats and styles. However, the current implementation of newforms is in very early state (I guess) so there are so many missing pieces. For example, I would like to have a float field which automatically validates the input to be a valid floating point number. So I have to implement it myself.
Validating floating point number is very easy by just trying to float(value)
. However, it is not complete yet since sual limitations of a floating point number are max_digits
and decimal_places
. Django alreay provides a set of validators including IsValidFloat()
so I will not write it again. Below is my FloatField
.
from django.utils.translation import gettext from django.core import validators from django.newforms import Field from django.newforms.util import ValidationError __all__ = ( 'FloatField', ) EMPTY_VALUES = (None, '') class FloatField(Field): def __init__(self, max_digits=None, decimal_places=None, *args, **kwargs): self.max_digits, self.decimal_places = max_digits, decimal_places super(FloatField, self).__init__(*args, **kwargs) def clean(self, value): """ Validates that float() can be called on the input. Returns the result of float(). Returns None for empty values. """ super(FloatField, self).clean(value) if value in EMPTY_VALUES: return None try: value = float(value) except (ValueError, TypeError): raise ValidationError(gettext(u'Enter a float number.')) v = validators.IsValidFloat(self.max_digits, self.decimal_places) try: v(value, None) except validators.ValidationError, e: raise ValidationError(gettext(u'Enter a float number.')) return value
And then use FloatField
as follows.
from django import newforms as forms from django.newforms.widgets import HiddenInput from mysite.myapp.forms import FloatField class ItemForm(forms.Form): lineno = forms.IntegerField(widget=HiddenInput,required=False) product = forms.IntegerField(widget=HiddenInput) unit = forms.IntegerField(widget=HiddenInput) unit_price = forms.CharField(max_length=100,widget=HiddenInput) quantity = FloatField(max_digits=19,decimal_places=4)
Tags: django, newforms, codenone, floatfield
- sugree's blog
- 3217 reads
Recent comments
2 years 11 weeks ago
2 years 15 weeks ago
2 years 16 weeks ago
2 years 16 weeks ago
2 years 17 weeks ago
2 years 19 weeks ago
2 years 19 weeks ago
2 years 19 weeks ago
2 years 19 weeks ago
2 years 20 weeks ago