【问题标题】:How to extend CheckboxInput for a list of checkboxes如何为复选框列表扩展 CheckboxInput
【发布时间】:2014-09-24 17:50:45
【问题描述】:

我目前正在使用这样的 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 的新手,我在试图弄清楚如何解决这个问题时遇到了一些麻烦。我将不胜感激任何可能提供某种方向的建议。

【问题讨论】:

    标签: python flask wtforms flask-wtforms


    【解决方案1】:

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

    【讨论】:

      【解决方案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)
      

      并以您的形式:

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

      对于稍微类似的问题,请查看this Q&A

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多