You might have seen my previous post lamenting the weirdnesses around number formatting in python. This spills over into Django; if you have DecimalFields in your models (especially if you are using the ModelForm object to create your forms.
The previous "format Decimal object as a string that any 10-year-old would expect" method is:
def dec_string(dec):(I added the isinstance() bit to protect me from myself =)
if isinstance(dec, Decimal):
if dec:
if dec.normalize().as_tuple().exponent > 0:
return "%d"%dec
else:
return "%s"%dec.normalize()
else:
return 0
else:
return dec
Since we know how to format this, all that remains to be done is to create a widget that automatically formats DecimalFields correctly.
class DecimalInput(TextInput):And then just use that in your form:
def render(self, name, value, attrs=None):
value = dec_string(value)
return super(DecimalInput, self).render(name, value, attrs)
class EnergyForm(ModelForm):
kwh = DecimalField(widget=DecimalInput(attrs={'size':'6'}))
There is more to the ModelForm, but that's what the docs are for, right?
No comments:
Post a Comment