如何扩展复选框列表的CheckboxInput

2024-04-19 14:30:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我当前使用的多复选框字段如下:

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还不熟悉,我在尝试如何解决这个问题时遇到了一些困难。如果有任何建议,我将不胜感激。在


Tags: ofthe列表widgetswidgetmultipleselectlist
2条回答

您可以使用如下自定义验证器:

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)

以你的形式:

^{pr2}$

对于一个稍微类似的问题,请看this Q&A。在

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

相关问题 更多 >