Everything submitted to Flask Form is a string, which always fails form validation

时间:2019-04-16 23:33:58

标签: python-3.x flask flask-wtforms

I am trying to get a basic Flask Form set up, but realizing that everything I submit to the form is read in as a string:

from flask import blueprints, render_template
from flask import request
from wtforms import Form, DecimalField,
from wtforms.validators import NumberRange
    class PredictionForm(Form):
        inputfield = DecimalField("Impressions", validators=[NumberRange(min=0.0, max=1.0, message="Not valid")
        anotherinput = DecimalField('View Rate', validators=[NumberRange(min=0.0, max=1.0, message="Not valid")])

    @blueprint.route("/", methods=["POST", "GET"])
    def index():
        form = PredictionForm()
        print(request.form)
        print(form.validate()) # this always returns False!
        if request.method == "POST":
            print(request.form)

When I print requests.form, I get the following output: ImmutableMultiDict([('inputfield', '0'), ('anotherinput', '0.5'))])

I think this is why my form validation continually returns false, since clearly any value that is a string is not a number between 0 and 1. How do I get Flask to recognize my input values as numbers?

If this is NOT the reason why my validation is failing, please do let me know as well.

Note: I am printing request.form to debug - so I can see what type of data is being passed into my form. I know I can clearly validate on the server-side, by doing something like

input_field = request.form['input_field'] if input_field.isnumber(): ... some more logic

However, all of this is happening on the backend server-side. The whole point of using these Flask validators is that I DON'T need to do this validation server-side. For instance, if I change my validation for a field called spend:

 class PredictionForm(Form):
        inputfield = DecimalField("Impressions", validators=[NumberRange(min=0.0, max=1.0, message="Not valid")
        anotherinput = DecimalField('View Rate', validators=[NumberRange(min=0.0, max=1.0, message="Not valid")])
        spend = DecimalField('Spend', validators=[DataRequired()])

This works perfectly on my frontend, since if I attempt to submit my form with no input for spend, I get this message: enter image description here

2 个答案:

答案 0 :(得分:1)

我只是对您要实现的目标感到困惑。为什么打印 request.form 如果您要将表单参数(例如电子邮件,phone_no)传递给flask,则可以这样做

email = request.form['email']
phone_no = request.form['phone_no']

如果您要验证实例 phone_no 为否 您可以

if not phone_no.isdigit():
    print ("phone no must be numbers")

因此,用于发送表单参数(例如电子邮件和phone_no )的代码将看起来像。您可以进行其他检查 代码

  @blueprint.route("/", methods=["POST", "GET"])
    def index():
        form = PredictionForm()
        print(request.form)
        print(form.validate()) # this always returns False!
        if request.method == "POST":
            print(request.form)

            email = request.form['email']
            phone_no = request.form['phone_no']

我的答案的更新部分:

如果要数字化,则应为integerfield。还要检查以确保该字段也影响您的模型

IntegerField('Telephone', [validators.NumberRange(min=0, max=10)]

请参阅文档link

答案 1 :(得分:0)

我发现了自己的问题-我没有将request.form传递给我的PredictionForm实例:

@blueprint.route("/", methods=["POST", "GET"])
def index():
    form = PredictionForm(request.form)
    form.validate() # this validates correctly now!

在前端,如果用户未输入Decimal值的有效数字,则他/她将收到错误消息。