X-Git-Url: https://asedeno.scripts.mit.edu/gitweb/?a=blobdiff_plain;f=bluechips%2Fwidgets%2F__init__.py;h=6e8ec966ce71d2e029d554d0f9bd9b865ac9ea62;hb=9458527642fab328a945d06daed04404c1ae2091;hp=a3b66d6b63354d506acafce0f2637f87f0aba1c3;hpb=26cf49d4e67b803b058972677f2c305822110639;p=bluechips.git diff --git a/bluechips/widgets/__init__.py b/bluechips/widgets/__init__.py index a3b66d6..6e8ec96 100644 --- a/bluechips/widgets/__init__.py +++ b/bluechips/widgets/__init__.py @@ -5,7 +5,7 @@ from tw.forms import validators from bluechips import model from bluechips.model import meta -from decimal import Decimal +from bluechips.model.types import Currency class UserSelect(forms.SingleSelectField): @staticmethod @@ -15,15 +15,58 @@ class UserSelect(forms.SingleSelectField): options = getUserList validator = validators.Wrapper( - to_python=meta.Session.query(model.User).get, - from_python=(lambda x: x.id)) + to_python=(lambda x: meta.Session.query(model.User).get(int(x))), + from_python=(lambda x: str(x.id))) + + def _is_option_selected(self, option_value, value): + if value is not None: + return option_value == value.id + else: + return False class AmountField(forms.TextField): size = 8 validator = validators.All( validators.Wrapper( - to_python=Decimal, - from_python=str), - validators.Regex(r'^[0-9]*(\.[0-9]{2})?$', not_empty=True)) + to_python=(lambda x: Currency(float(x) * 100)), + from_python=Currency.__str_no_dollar__), + validators.Regex(r'^\-?[0-9]*(\.[0-9]{2})?$')) + +# This is virtually copied from formencode.validator.FieldsMatch, but +# I wanted my own version for fields that shouldn't match +class FieldsDontMatch(validators.FormValidator): + """ + Tests that the given fields do not match. + """ + + show_match = False + field_names = None + valid_partial_form = True + __unpackargs__ = ('*', 'field_names') + + messages = { + 'invalid': "Fields match" + } + + def validate_partial(self, field_dict, state): + for name in self.field_names: + if not field_dict.has_key(name): + return + self.validate_python(field_dict, state) + + def validate_python(self, field_dict, state): + errors = {} + for ref_index, ref in enumerate(self.field_names): + for name in self.field_names[ref_index+1:]: + if field_dict.get(name, '') == field_dict.get(ref, ''): + errors[name] = self.message('invalid', state) + if errors: + error_list = errors.items() + error_list.sort() + error_message = '
\n'.join( + ['%s: %s' % (name, value) for name, value in error_list]) + raise validators.Invalid(error_message, + field_dict, state, + error_dict=errors) -__all__ = ['UserSelect', 'AmountField'] +__all__ = ['UserSelect', 'AmountField', 'FieldsDontMatch']