简体   繁体   English

烧瓶WTForm验证对SelectField失败...为什么?

[英]Flask WTForm validation failing for SelectField…why?

I'm using Flask and WTForm to make a web app, so far my other two fields validate fine, but the SelectField is throwing the error 'Please choose a pet.' 我正在使用Flask和WTForm制作一个Web应用程序,到目前为止,我的其他两个字段都可以很好地验证,但是SelectField抛出错误“请选择一只宠物”。 as specified by myself ie it thinks thinks that it isn't receiving a valid input. 正如我自己指定的,即认为自己没有收到有效的输入。 The SelectField.choices match up to the options rendered into HTML so what am I doing wrong? SelectField.choices与呈现为HTML的选项匹配,所以我在做什么错呢?

app.py app.py

from flask_wtf import Form
from flask_wtf.csrf import CSRFProtect
from wtforms import IntegerField, StringField, SelectField, validators, 
ValidationError
from flask import Flask, request, flash, render_template

app = Flask(__name__)
app.secret_key = 'xxxxxxxxxxxx'
csrf = CSRFProtect(app)


pChoices = [('-1', '-----'),
            ('0', 'Cat'),
            ('1', 'Dog'),
            ('2', 'Parrot'),
            ('3', 'Hamster')]


class paymentForm(Form):
    productF = SelectField('productF', [validators.input_required("Please choose a pet.")], choices=[pChoices], coerce=int)
    buyer_id = StringField('buyer', [validators.input_required("Please enter your name.")])
    paid = DecimalField('paid', [validators.input_required("please enter payment amount")])


@app.route('/', methods=['POST', 'GET'])
def index():
    form = paymentForm(request.form, csrf_enabled=True)
    if form.validate_on_submit():
        flash('Order Placed Successfully', 'success')
        data = form.data
        record_order(data)
        print(data['price'])
        return render_template('confirmation.jinja',
                               pets=PETS,
                               title='Confirmation Page',
                               form=form, error=form.errors,
                               ** context)
    elif not form.validate_on_submit:
        flash('Submission error, please check the form', 'success')
    return render_template('index.jinja',
                               title='Order Form',
                               form=form,
                               error=form.errors,
                               **context)

if __name__ == '__main__':
    app.run(debug=True, use_reloader=True)

index.jinja index.jinja

{% extends 'base.jinja' %}

{% block main %}
  <form method="post">
    <div class="form-group row">
      <label for="product" class="col-sm-2 form-control-label">Pet:</label>
      <div class="col-sm-8">
        <select id="productF" class="form-control" name="pet" onchange="Update()">
          <option value="-1">-----</option>
          {% for pet in pets %}
            <option value="{{ loop.index -1 }}">{{ pet.name }}</option>
          {% endfor %}
        </select>
      </div>
    </div>
    <div class="form-group row">
      <label for="buyer" class="col-sm-2 form-control-label">Buyer:</label>
      {% for message in form.buyer_id.errors %}
         <div>{{ message }}</div>
      {% endfor %}
      <div class="col-sm-10">
        <input type="text" class="form-control" id="buyer_id" name="buyer_id" placeholder="Buyer" value="{{ buyer_id }}" required>
      </div>
    </div>
    <div class="form-group row">
      <label for="paid" class="col-sm-2 form-control-label">Amount Paid:</label>
      {% for message in form.paid.errors %}
         <div>{{ message }}</div>
      {% endfor %}
      <div class="col-sm-10">
        <input type="text" class="form-control" id="paid" name="paid" placeholder="Amount Paid" value="{{ paid }}" required>
      </div>
    </div>
    {% if form.errors %}
    {{ form.errors }}
    {% endif %}
    <div class="form-group row">
      <div class="col-sm-offset-2 col-sm-10">
        <button type="submit" class="btn btn-primary">Place Order</button>
      </div>
    </div>
        <input type="hidden" name="csrf_token" value="{{ csrf_token() 
}}"/>
  </form>


{% endblock %}

edit I have updated the code with productF as the field name in the jinja file and I still receive the error. 编辑我已使用productF作为jinja文件中的字段名称更新了代码,但仍然收到错误。 The Pets object is loaded into the HTML page as a JSON object instead of app.py but as far as I can tell the values are identical; Pets对象作为JSON对象而不是app.py加载到HTML页面中,但是据我所知,值是相同的。 this is how the select element appears from the inspector: 这是检查器中选择元素的显示方式:

<select id="product" class="form-control" name="product">
          <option value="-1">-----</option>         
            <option value="0">Cat</option>          
            <option value="1">Dog</option>          
            <option value="2">Parrot</option>          
            <option value="3">Hamster</option>          
        </select>

You're defining pChoices as a list 您正在将pChoices定义为列表

pChoices = [('-1', '-----'),
            ('0', 'Cat'),
            ('1', 'Dog'),
            ('2', 'Parrot'),
            ('3', 'Hamster')]

But then wrapping it in another list in the SelectField definition: 但是,然后将其包装在SelectField定义的另一个列表中:

productF = SelectField(..., choices=[pChoices], ...)

Using choices=pChoices should fix it. 使用choices=pChoices应该修复它。

Edit: you also have pet as the field name in the form jinja template, you probably want to use productF . 编辑:您也有pet作为表单jinja模板中的字段名称,您可能要使用productF

Edit 2: there's a mismatch on the way you're defining the values for pChoices and the field coercion. 编辑2:定义pChoices和字段强制的值的方式不匹配。 Either remove coerce=int from the form field or set the first value of the tuples in pChoices to be integers, not strings. 从表单字段中删除coerce=int或将pChoices中的元组的第一个值设置为整数,而不是字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM