Skip to content

Instantly share code, notes, and snippets.

Last active June 8, 2023 18:09
Show Gist options
  • Save doobeh/4668212 to your computer and use it in GitHub Desktop.
Save doobeh/4668212 to your computer and use it in GitHub Desktop.
Checkbox WTForms Example (in Flask)
<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<form method="post">
{{ form.hidden_tag() }}
{{ form.example }}
<button type="submit">Submit</button>
from flask import Flask, render_template
from flask_wtf import FlaskForm
from wtforms import widgets, SelectMultipleField
SECRET_KEY = 'development'
app = Flask(__name__)
class MultiCheckboxField(SelectMultipleField):
widget = widgets.ListWidget(prefix_label=False)
option_widget = widgets.CheckboxInput()
class SimpleForm(FlaskForm):
string_of_files = ['one\r\ntwo\r\nthree\r\n']
list_of_files = string_of_files[0].split()
# create a list of value/description tuples
files = [(x, x) for x in list_of_files]
example = MultiCheckboxField('Label', choices=files)
def hello_world():
form = SimpleForm()
if form.validate_on_submit():
return render_template("success.html",
print("Validation Failed")
return render_template('example.html',form=form)
if __name__ == '__main__':
<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
{{ data }}
Copy link

Thanks for this code example.

I was struggling with validating the form though. I needed at least one checkbox to be checked. Above comments mentioning form.validate_on_submit() or form.is_submitted() unfortunately didn't help.

After some googling I stumbled on this stackoverflow answer that finally helped.

My final custom validator code:

def validate(self, extra_validators=None):
  if super().validate(extra_validators):
    if not request.form.getlist('example'):
      self.example.errors.append('At least one checkbox must be selected')
      return False
      return True
    return False

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment