Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a list of BooleanField using wtforms

My goal is to query a list of users from a database then have a BooleanField next to each person's name. Each person can be checked whether they will be submitted to the form or not. I have tried using SelectMultipleField, but it seems to only submit one value, and FieldList really has no examples so I am not sure if they may be what I am looking for or not. I am new to WTForms and I am not sure what is the best option to use for what I am trying to do.

Example: enter image description here

like image 614
user1953222 Avatar asked Oct 20 '25 17:10

user1953222


1 Answers

I'm going to assume you're using Flask-SQLAlchemy to handle your data model because you make no mention of how you're accessing you database.

A form defined like:

class ExampleForm(Form):
    user = QuerySelectMultipleField(
        'User',
        query_factory=lambda: User.query.all(),
        widget=widgets.ListWidget(prefix_label=False),
        option_widget=widgets.CheckboxInput()
    )
    submit = SubmitField('Submit')

Will generate a list of checkboxes for each user, which then can be handled as required. The template to render the form could then just be:

<form action="" method="POST">
    {{ form.csrf_token }}
    {{ form.user }}
    {{ form.submit }}
</form>

And the route code would just be along the lines of:

@app.route('/', methods=['post','get'])
def home():
    form = ExampleForm()
    if form.validate_on_submit():
        return "{}".format(form.user.data)
    return render_template('example.html', form=form)
like image 65
Doobeh Avatar answered Oct 22 '25 07:10

Doobeh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!