#3238: A FloatField for those who need one in newforms
---------------------------------+------------------------------------------
Reporter: [EMAIL PROTECTED] | Owner: adrian Type: enhancement | Status: new Priority: normal | Milestone: Component: django.newforms | Version: SVN Severity: normal | Keywords: newforms fields floatfield
---------------------------------+------------------------------------------
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.

{{{
#!python
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

--
Ticket URL: <http://code.djangoproject.com/ticket/3238>
Django <http://code.djangoproject.org/>
The web framework for perfectionists with deadlines.
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Django 
updates" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-updates?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to