python - formencode Schema add fields dynamically -
let's take, example, user schema
site admin sets number of requested phone numbers:
class myschema(schema): name = validators.string(not_empty=true) phone_1 = validators.phonenumber(not_empty=true) phone_2 = validators.phonenumber(not_empty=true) phone_3 = validators.phonenumber(not_empty=true) ...
somehow thought do:
class myschema(schema): name = validators.string(not_empty=true) def __init__(self, *args, **kwargs): requested_phone_numbers = session.query(...).scalar() n in xrange(requested_phone_numbers): key = 'phone_{0}'.format(n) kwargs[key] = validators.phonenumber(not_empty=true) schema.__init__(self, *args, **kwargs)
since read in formencode docs:
validators use instance variables store customization information. can use either subclassing or normal instantiation set these.
and schema
called in docs compound validator , subclass of fancyvalidator
guessed it's correct.
but not work: added phone_n
ignored , name
required.
update:
also tried both overriding __new__
, __classinit__
before asking no success...
i had same problem, found solution here: http://markmail.org/message/m5ckyaml36eg2w3m
all thing use add_field method of schema in youre init method
class myschema(schema): name = validators.string(not_empty=true) def __init__(self, *args, **kwargs): requested_phone_numbers = session.query(...).scalar() n in xrange(requested_phone_numbers): key = 'phone_{0}'.format(n) self.add_field(key, validators.phonenumber(not_empty=true))
i don't think there's need call parent init
Comments
Post a Comment