2011-07-21 22 views
3

讓我們舉個例子,一個用戶Schema在站點管理員設置要求的電話號碼數量:formencode架構字段添加動態

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) 
    ... 

不知怎的,我以爲我可以簡單地做:

class MySchema(Schema): 
    name = validators.String(not_empty=True) 
    def __init__(self, *args, **kwargs): 
     requested_phone_numbers = Session.query(...).scalar() 
     for n in xrange(requested_phone_numbers): 
      key = 'phone_{0}'.format(n) 
      kwargs[key] = validators.PhoneNumber(not_empty=True) 
     Schema.__init__(self, *args, **kwargs) 

因爲我在FormEncode docs中讀到:

驗證器使用實例變量來存儲他們的customiza信息 信息。您可以使用子類化或正常實例化來設置這些。

Schema被稱爲文檔作爲複合驗證,是FancyValidator子類,所以我猜它是正確的。

但這不起作用:只需添加phone_n就會被忽略,只需要name

更新:

此外,我都嘗試重寫__new____classinit__沒有成功前問...

回答

5

我有同樣的問題,我在這裏找到了解決方案: http://markmail.org/message/m5ckyaml36eg2w3m

所有的事情就是使用你的模式的add_field方法init方法

class MySchema(Schema): 
    name = validators.String(not_empty=True) 

    def __init__(self, *args, **kwargs): 
     requested_phone_numbers = Session.query(...).scalar() 
     for n in xrange(requested_phone_numbers): 
      key = 'phone_{0}'.format(n) 
      self.add_field(key, validators.PhoneNumber(not_empty=True)) 

我不認爲有必要調用父初始化

+0

是的!謝謝!經過一個多小時尋找解決方案後,這才解決了我的問題。 – Brodan