]> asedeno.scripts.mit.edu Git - bluechips.git/blob - bluechips/widgets/__init__.py
9da303d68945c5bcc028b140d8ec49a426651e81
[bluechips.git] / bluechips / widgets / __init__.py
1 from tw import forms
2
3 from tw.forms import validators
4
5 from bluechips import model
6 from bluechips.model import meta
7
8 from bluechips.lib.base import _
9
10 from decimal import Decimal
11
12 class UserSelect(forms.SingleSelectField):
13     @staticmethod
14     def getUserList():
15         for u in meta.Session.query(model.User):
16             yield (u.id, u.name)
17     
18     options = getUserList
19     validator = validators.Wrapper(
20         to_python=(lambda x: meta.Session.query(model.User).get(int(x))),
21         from_python=(lambda x: str(x.id)))
22     
23     def _is_option_selected(self, option_value, value):
24         if value is not None:
25             return option_value == value.id
26         else:
27             return False
28
29 class AmountField(forms.TextField):
30     size = 8
31     validator = validators.All(
32         validators.Wrapper(
33             to_python=Decimal,
34             from_python=str),
35         validators.Regex(r'^[0-9]*(\.[0-9]{2})?$', not_empty=True))
36
37 # This is virtually copied from formencode.validator.FieldsMatch, but
38 # I wanted my own version for fields that shouldn't match
39 class FieldsDontMatch(validators.FormValidator):
40     """
41     Tests that the given fields do not match.
42     """
43     
44     show_match = False
45     field_names = None
46     valid_partial_form = True
47     __unpackargs__ = ('*', 'field_names')
48     
49     messages = {
50         'invalid': _("Fields match")
51         }
52     
53     def validate_partial(self, field_dict, state):
54         for name in self.field_names:
55             if not field_dict.has_key(name):
56                 return
57         self.validate_python(field_dict, state)
58     
59     def validate_python(self, field_dict, state):
60         errors = {}
61         for ref_index, ref in enumerate(self.field_names):
62             for name in self.field_names[ref_index+1:]:
63                 if field_dict.get(name, '') == field_dict.get(ref, ''):
64                     errors[name] = self.message('invalid', state)
65         if errors:
66             error_list = errors.items()
67             error_list.sort()
68             error_message = '<br>\n'.join(
69                 ['%s: %s' % (name, value) for name, value in error_list])
70             raise validators.Invalid(error_message,
71                                      field_dict, state,
72                                      error_dict=errors)
73
74 __all__ = ['UserSelect', 'AmountField', 'FieldsDontMatch']