tookas92
tookas92

Reputation: 225

WTForms booleanfield always return True

I have written custom 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

Rendered it nicely in template but everytime when i try to send it and checkboxes are False it sends always True as it is in append_entry. Here is how i check my input data.

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)

It looks like form always sends default value no matter if the checkbox is True or False I have also defined form prefill and if I manually set the value in database to False it renders input properly as False but when I send the form again(no matter what checkboxes statuses are) it overwrites the database to True. There is definitely problem that the form doesnt see edited values. How can i solve it?

Upvotes: 1

Views: 773

Answers (1)

Nick K9
Nick K9

Reputation: 4663

You are setting the value of the form fields in the init method of the form itself. This is likely overriding the values which have been set on the form from the request.form as part of loading the relevant view.

You should instead populate the fields as needed in scaffold_form() or 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

Upvotes: 1

Related Questions