BTW, I am aware of the ability to create your own custom model field
class with a custom `validate()` method like my following example. I'm
also aware of using a model's clean() method to raise logical
validation errors, like if their email is a gmail address and they
they specify that they are a Yahoo user, you might raise
ValidationError("You liar. You use Gmail"), and so on.

My custom field and below an explanation of another pitfall of form
validation:

class CurrencyField(models.DecimalField):
    """
    Only changes output into a quantized format. Everything else is
the same.
    Later I will possibly add currency symbol support.
    """
    description = 'A double decimal representing money'
    __metaclass__ = models.SubfieldBase

    def __init__(self, *args, **kwargs):
        kwargs['max_digits'] =  8
        kwargs['decimal_places'] = 2
        super(CurrencyField, self).__init__(*args, **kwargs)

    def to_python(self, value):
        try:
            return super(CurrencyField,
self).to_python(value).quantize(Decimal('0.01'))
        except AttributeError:
            return None

    def validate(self, value, model_instance):
        """
        Check for anything other than numbers, a decimal, and a dollar
sign, and
        raise a singular error on success.
        """
        # This allows for a $ symbol as well (but that's not supported
by forms.fields.DecimalField)
        reo = re.compile(r'^\$?\s*((?=\d*\.|\d)\d*(?:\.\d*)?)$')
        if not reo.search(str(value)):
            raise ValidationError(u'Enter a valid "money value"
consisting of digits a single decimal place and an optional dollar
sign.')
        super(CurrencyField, self).validate(value, model_instance)

    def get_db_prep_value(self, value):
        """
        Remove dollar signs.
        """
        return re.sub(r'[\d\.]', '', str(value))

The above model does everything necessary but some of it isn't even
use all of the logic with Django forms. If I'm using forms, the user
cannot put a "$" symbol because before my code can possibly normalize
the data and remove the dollar sign, the user is warned about it not
being a decimal. However, decimal is what makes most sense to use, and
I don't want to have to create a custom form for this model just so
that I can strip a dollar sign from one field.

-- 
You received this message because you are subscribed to the Google Groups 
"Django developers" group.
To post to this group, send email to django-develop...@googlegroups.com.
To unsubscribe from this group, send email to 
django-developers+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-developers?hl=en.

Reply via email to