Customising Fields

Here's an example of how we created a MoneyField that knows how to validate a currency value. Both parser and formatter are modules that we wrote to convert between formats. Our modules deal in dollars and cents but that's hidden from the application code.

Note that the parser needs to be able to parse the output of the formatter: the field will be initialised with the formatter's output when it is rendered. It doesn't seem unreasonable to accept "$5.50" if that's the format that the application is presenting to the user.

   1 import parser, formatter
   2 
   3 class MoneyField(FloatField):
   4 
   5     def validate(self, form, s):
   6         s = s.strip()
   7         if not self.required and not s:
   8             return
   9         try:
  10             parser.money(s)
  11         except ValueError, e:
  12             raise FieldValidationError('Invalid value "%s" for money' % s)
  13 
  14     def get_merge_value(self, s):
  15         s = s.strip()
  16         if not self.required and not s:
  17             return
  18         return parser.money(s)
  19 
  20     def get_display_value(self, ctx, form):
  21         return formatter.money(self.get_value())

None: Customising_fields (last edited 2011-02-15 06:05:17 by localhost)