Added MIT license.
[zzz-floof.git] / floof / model / forms.py
1 """FormEncode validators."""
2
3 import formencode
4
5 from floof.model.users import User, UserRelationshipTypes
6
7 class UniqueExistingRow(formencode.FancyValidator):
8 """Given a column object, converts a unique value from that column into the
9 corresponding row object.
10 """
11 def __init__(self, table, column):
12 self.table = table
13 self.column = column
14 super(formencode.FancyValidator, self).__init__()
15
16 def _to_python(self, value, state):
17 try:
18 row = self.table.query.filter(self.column == value).one()
19 except BaseException, e:
20 raise formencode.Invalid(
21 'No unique row.',
22 value, state
23 )
24 return row
25
26 ### user_settings
27
28 class UserRelationshipToggleForm(formencode.Schema):
29 target_user = UniqueExistingRow(User, User.id)
30 type = formencode.compound.Pipe(
31 formencode.validators.Int(),
32 formencode.validators.OneOf(
33 [v for (k, v) in UserRelationshipTypes.__dict__.items()
34 if k[0] != '_']
35 ),
36 )
37 add_remove = formencode.validators.OneOf([u'add', u'remove'])