问题
I'm making a WTForm which takes Decimals as inputs, and I'm trying to restrict input to a range of numbers (between 0 and 10 inclusive). However, the validator NumberRange
doesn't seem to do anything.
Python (using flask):
from flask import render_template
from flask_wtf import FlaskForm
from wtforms import DecimalField, SubmitField, validators
class NumberForm(FlaskForm):
question = DecimalField('Question 1',
[validators.NumberRange(min=0, max=10, message="blah"),
validators.Optional()])
submit = SubmitField('Submit')
@app.route('some_route/', methods=['GET', 'POST])
def page():
form = NumberForm()
if form.validate_on_submit():
return some_success_or_other
return render_template('page.html', form=form)
HTML:
<form method="POST">
<div class="form-group-row">
{{ form.hidden_tag() }}
{{ form.question.label }}
<div>
{{ form.question }}
</div>
</div>
<div class="form-group-row">
{{ form.submit }}
</div>
</form>
The question
field will be submitted whatever value I input. I thought it wouldn't allow text, nor would it allow negative numbers, nor numbers outside the range (e.g. 10000).
I've tried changing the NumberRange
min and max to 0.0
and 10.0
. I've tried taking out the message arguments. I've tried taking out the Optional
validator. But none of these prevents me entering out of range numbers in the form.
(When I replaced Optional
with DataRequired
, the form would not submit unless there was data in the field, so that validator worked at least.)
Anyone know what I'm doing wrong?
Edit: it seems the problem was split into two parts: no validation, and validation messages not flashing. The answer below fixes the lack of validation.
回答1:
Apparently your application is not correctly configured. The code should look like this:
from flask_wtf import FlaskForm
from wtforms import SubmitField, DecimalField
from wtforms.validators import NumberRange
class NumberForm(FlaskForm):
question = DecimalField('Question 1', validators=[NumberRange(min=0, max=10, message='bla')])
submit = SubmitField('Submit')
来源:https://stackoverflow.com/questions/53048287/wtforms-not-validating-numberrange