如何扩展CheckboxInput以获取复选框列表

时间:2014-09-24 17:50:45

标签: python flask wtforms flask-wtforms

我目前正在使用这样的MultiCheckboxField:

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的新手,我在试图找出如何解决问题方面遇到了一些麻烦。对于任何可能提供某种指导的建议,我将不胜感激。

2 个答案:

答案 0 :(得分:0)

使用自定义小部件查看FieldList和FormField http://wtforms.readthedocs.org/en/latest/fields.html#field-enclosures

答案 1 :(得分: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