WTForms not validating NumberRange

会有一股神秘感。 提交于 2019-12-25 01:45:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!