WTForms布尔值字段始终返回True

时间:2019-06-12 11:46:01

标签: flask flask-wtforms wtforms flask-admin

我写了自定义FieldList

    class EventForm(Form):
        enabled = BooleanField()
        user_role = IntegerField()


    class EventsForm(Form):
        user_roles = FieldList(FormField(EventForm))
        section_name = StringField()

class CompanyForm(BaseForm):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._populate_event_permissions()

        def _populate_event_permissions(self):
        permissions = get_all_event_permissions()
        for event, value in permissions.items():
            form_field = self.event.append_entry(
                data={'section_name': event})
            field_1 = form_field.user_roles.append_entry(
                data={'enabled': True, 'user_role': 8})
            field_1.enabled.label.text = 'Participant'
            field_1.enabled.name = value
            field_2 = form_field.user_roles.append_entry(
                data={'user_role': 9})
            field_2.enabled.label.text = 'Organizer'
            field_2.enabled.name = value
            field_3 = form_field.user_roles.append_entry(
                data={'user_role': 10})
            field_3.enabled.label.text = 'Admin'
            field_3.enabled.name = value

在模板中很好地呈现了它,但是每次我尝试发送它并且复选框为False时,它总是像在True中一样发送append_entry。这是我检查输入数据的方法。

class MyView(BaseModelView):
    def on_model_change(self, form, model, is_created):
        for section in form.event.entries:
            for entry in section.user_roles.entries:
                print(entry.enabled.data)

无论复选框是True还是False,看来表单总是发送default value我也定义了表单预填充,并且如果我手动将数据库中的值设置为False,它会正确地将输入呈现为False,但是当我发送时再次使用该表单(无论处于何种复选框状态),都将数据库覆盖为True。绝对存在表单看不到已编辑值的问题。我该怎么解决?

1 个答案:

答案 0 :(得分:0)

您正在表单本身的init方法中设置表单字段的值。在加载相关视图时,这很可能会覆盖request.form在表单上设置的值。

您应该根据需要在scaffold_form()create_form() / edit_form()中填充字段。

class MyView(BaseModelView):
    def scaffold_form(self):
        form = super(MyView, self).scaffold_form()

        permissions = get_all_event_permissions()
        for event, value in permissions.items():
            form_field = self.event.append_entry(data={'section_name': event})
            # etc.

        return form