Not sure if this should be wrapped up in a patch, or what, but I just thought I'd put this out there in case anyone wanted to use it.
import re
import decimal
from django.newforms import *
float_regex = re.compile(
r'\d+.\d+'
)
class FloatField(RegexField):
def __init__(self, max_digits=None, decimal_places=None,max_value=None, min_value=None, required=True, widget=None, label=None, initial=None):
self.max_value, self.min_value = decimal.Decimal(max_value or 'inf'), decimal.Decimal(min_value or '-inf')
self.max_digits, self.decimal_places = max_digits, decimal_places
RegexField.__init__(self, regex=float_regex, error_message="Please enter a valid decimal number", required=required, widget=widget, label=label, initial=initial)
def clean(self, value):
super(FloatField, self).clean(value)
digits,decimals = value.split(".")
if not self.required and value in EMPTY_VALUES:
return u''
try:
value = decimal.Decimal(value)
except:
raise ValidationError("Enter a decimal number")
if self.max_value is not None and value > self.max_value:
raise ValidationError("Ensure that value is less than or equal to %s" % self.max_value)
if self.min_value is not None and value < self.min_value:
raise ValidationError("Ensure that value is greater than or equal to %s" % self.min_value)
if self.max_digits is not None and len(digits) > self.max_digits:
raise ValidationError("Ensure that the number of digits is less than or equal to %s" % self.max_digits)
if self.decimal_places is not None and len(decimals) > self.decimal_places:
raise ValidationError("Ensure that the number of decimal places is less than or equal to %s" % self.decimal_places)
return value