Differences between revisions 1 and 4 (spanning 3 versions)
Revision 1 as of 2009-11-19 04:41:20
Size: 826
Editor: BenGolding
Comment:
Revision 4 as of 2011-02-15 06:05:17
Size: 1172
Editor: localhost
Comment: converted to 1.6 markup
Deletions are marked like this. Additions are marked like this.
Line 3: Line 3:
Here's an example of how we created a MoneyField that knows how to validate a currency (dollar) value. Both {{{parser}}} and {{{formatter}}} are modules that we wrote to convert between formats. 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.
Line 12: Line 14:
        if not self.required and s == '':         if not self.required and not s:
Line 21: Line 23:
        if not self.required and s == '':         if not self.required and not s:

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)