Hello,

I want to store costs (prices) in my DB. The obvious field type is
Integer, storing the cost in cents (strings prevent arithmetic
operations, floats are entirely inappropriate).

For input via a form, I have a nice CostField defined as follows:

class CostField(forms.CharField):
        def validate(self, value):
                super(CostField, self).validate(value)
                if not re.match(r'^\d+(\.\d\d)?$', value):
                        raise forms.ValidationError("Enter a price in the form 
1.50")

        def clean(self, value):
                value = super(CostField, self).clean(value)
                return float(value) * 100

So it starts as a CharField, gets validated appropriately and then
converted to the cents-only equivalent.

But for output in templates, I have not found an elegant solution.
Currently I am using this:

def h_price(price):
        dollars = price / 100
        cents = str(price % 100)
        if len(cents) == 1:
                cents = '0%s' % cents
        return '%s.%s' % (dollars, cents)

class Whatever(models.Model):
        price = models.IntegerField()
        @property
        def h_price(self):
                return h_price(self.price)

But the problem is that I need obviously to repeat the property
definition for every usage of money in the schema.

I tried creating a custom field as follows:

class CostField(models.IntegerField):
        def h(self):
                return 'hello'

and using this in a template like this: {{ item.price.h }}

But this doesn't work, it doesn't even call my h() function.

Can anyone point me in the right direction?

Thankyou :-)

Darren

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

Reply via email to