2014-09-24 50 views
0

我目前使用MultiCheckboxField这样一个复选框列表:如何延长CheckboxInput为

class MultiCheckboxField(SelectMultipleField): 
    """ 
    A multiple-select, except displays a list of checkboxes. 

    Iterating the field will produce subfields, allowing custom rendering of 
    the enclosed checkbox fields. 
    """ 

    widget = widgets.ListWidget(prefix_label=False) 
    option_widget = widgets.CheckboxInput() 

生成复选框列表。我想以这样的方式扩展此列表,以允许某些列表条目具有关联的TextInput字段。当该框被选中时,相应的文本输入是必需的。

我是Flask和WTForms的新手,我在尝试弄清楚如何解决问题时遇到了一些麻烦。我会很感激任何可能提供某种方向的建议。

回答

0

您可以使用自定义验证程序是这样的:

class RequiredIfChoice(validators.DataRequired): 
    # a validator which makes a field required if 
    # another field is set and has a truthy value 

    def __init__(self, other_field_name, desired_choice, *args, **kwargs): 
     self.other_field_name = other_field_name 
     self.desired_choice = desired_choice 
     super(RequiredIfChoice, self).__init__(*args, **kwargs) 

    def __call__(self, form, field): 
     other_field = form._fields.get(self.other_field_name) 
     if other_field is None: 
      raise Exception('no field named "%s" in form' % self.other_field_name) 
     for value, label, checked in other_field.iter_choices(): 
      if label == self.desired_choice and checked: 
       super(RequiredIfChoice, self).__call__(form, field) 

,并在您的形式:

class MyForm(Form): 
    """ 
    Your form. 
    """ 
    multi = MultiCheckboxField('Multibox', choices=[(1, 'First'), (2, 'Second')], coerce=int) 
    multitext = StringField('SubText', [RequiredIfChoice('multi', 'Second')]) 

一个稍微相似问题看看this Q&A