BooleanField does not honor default value
ademaro opened this issue · comments
I'm having issues with rendering a BooleanField correctly
from flask_wtf import FlaskForm
from wtforms import BooleanField
class TestForm(FlaskForm):
check = BooleanField("mycheckbox", default="checked")
But it renders unchecked...
Works correctly if written like this:
class TestForm(FlaskForm):
check = BooleanField("mycheckbox", render_kw={"checked": True})
Environment: MacOS 12.0.1
- Python version: 3.9.8
- Flask-WTF version: 0.15.1
- Flask version: 2.0.2
Presumably it should be default=True
.
@davidism In general, it does not matter, but I tried with your version, the effect is the same...
I just tested it using the same environment and this code and it worked fine.
from flask import Flask
from flask_wtf import FlaskForm
from wtforms import BooleanField
app = Flask(__name__)
app.secret_key = "VERY SECURE"
class TestForm(FlaskForm):
check = BooleanField("mycheckbox", default="checked")
check2 = BooleanField("mycheckbox", default=True)
@app.route("/")
def index():
form = TestForm()
return form.check() + form.check2()
This is the result:
<input checked id="check" name="check" type="checkbox" value="y"><input checked id="check2" name="check2" type="checkbox" value="y">⏎
My variant not worked about this line: form = TestForm(request.form)
from flask import Flask, request
from flask_wtf import FlaskForm
from wtforms import BooleanField
app = Flask(__name__)
app.secret_key = "VERY SECURE"
class TestForm(FlaskForm):
check = BooleanField("mycheckbox", default="checked")
check2 = BooleanField("mycheckbox", default=True)
@app.route("/")
def index():
form = TestForm(request.form)
return form.check() + form.check2()
Now all good, thanks)
# ...
if request.method == 'POST':
form = TestForm(request.form)
else:
form = TestForm()
Just a short note: flask-wtf provides validate_on_submit which checks the request method and validates the data. So if you do not intend to skip validation its probably good yo use this method. Here is a small code example:
@app.route('/submit', methods=['GET', 'POST'])
def submit():
form = MyForm()
if form.validate_on_submit():
return redirect('/success')
return render_template('submit.html', form=form)
@jnnkB Thanks, but in your example, saving the filled form fields after submitting the form, if errors occur in any of the fields, will not work in your example. Previously, I always passed the request.form
to the constructor of the form class:
form = MyForm(request.form)
But this stopped working with checkboxes, so I had to make an additional check:
if request.method == 'POST':
form = MyForm(request.form)
else:
form = MyForm()
After these checks, of course, the real code contains if form.validate_on_submit ():
.
I don't know how much better it can be done, but for now, like this...