为什么我的SelectField和RadioField永远不会验证?

时间:2017-06-02 13:02:09

标签: python flask wtforms

我正在尝试使用Flask(0.12),WtForms(2.1)和SQLAlchemy(1.1.5)构建一个非常简单的表单。

form.py:

from flask_wtf import Form
from wtforms import StringField, BooleanField, RadioField, SelectField, IntegerField, SubmitField
from wtforms.validators import DataRequired
from app.models.theme import Theme
from app.models.type import Type
from app.models.user import User

class CreateFolderForm(Form):
    responsible = SelectField('Responsible', choices=User.form_list())
    anomaly_type = SelectField('Anomaly type', choices=Type.form_list())
    theme = SelectField('Theme', choices=Theme.form_list())
    corrective_needed = BooleanField('Corrective action needed')
    cost = IntegerField('Cost')
    risk_level = RadioField('risk level', choices=[(1, '1'), (2, '2'), (3, '3'), ])
    risk_occurrence = RadioField('risk occurrence', choices=[(1, '1'), (2, '2'), (3, '3'), ])
    submit = SubmitField('Create')

template.html:

{% block content %}
    <h1>New Folder</h1>
    <div class="form-group">
        <form action="" method="post" name="new folder">
            {{ form.csrf_token }}
            Responsible : {{ form.responsible }} <br/>
            Anomaly Type : {{ form.anomaly_type }} <br/>
            Theme : {{ form.theme }} <br/>
            Corrective Action needed : {{ form.corrective_needed }} <br/>
            Cost : {{ form.cost }}<br/>
            Risk Level : {{ form.risk_level }}<br/>
            Occurrence Level : {{  form.risk_occurrence  }}<br/>
            {{ form.submit }}
        </form>
    </div>
{% endblock %}

controller.py:

from datetime import datetime
from flask import redirect, url_for, flash
from app import app
from flask import render_template
from app import db
from app.models.qualityFolder import QualityFolder
from app.models.user import User
from app.forms.create_folder_form import CreateFolderForm

@app.route('/folder/add', methods=['GET', 'POST'])
def add_folder():
    form = CreateFolderForm()
    print(form.responsible.validate(form))
    print(form.responsible.errors)
    if form.validate_on_submit():
        print(form)
        folder = QualityFolder()
        folder.anomaly_type_id = int(form.anomaly_type.data)
        folder.corrective_action_wanted = form.corrective_needed.data
        folder.cost = int(form.cost.data)
        folder.creation_date = datetime.now()
        if form.credit.data:
            folder.credit = int(form.credit.data)
        folder.risk_level = int(form.risk_level.data)
        folder.occurrence_level = int(form.risk_occurrence)
        db.session.add(folder)
        db.session.commit()
        return redirect(url_for('index'))
    return render_template('create/folder_form.html', title='New Folder', form=form)

form.responsible.validate(form)会返回False,但print(form.responsible.errors)会返回一个空列表。我对“异常类型”,“主题”,“风险等级”和“风险发生”都有同样的问题。

注意:form_list方法如下:

@staticmethod
def form_list():
    themes = Theme.query.all()
    themes_list = []
    for theme in themes:
        themes_list.append([theme.id, theme.label])
    return themes_list

为什么我的表单不是“validate_on_submit”,并且我的字段是否返回“False”?

1 个答案:

答案 0 :(得分:0)

来自WTForms docs

  

请注意,choices关键字仅评估一次,因此如果您愿意   要创建动态下拉列表,您需要分配选项   实例化后列出到该字段。


根据文档页面示例,您必须执行以下操作:

class CreateFolderForm(Form):
    responsible = SelectField('Responsible', coerce=int)

@app.route('/folder/add', methods=['GET', 'POST'])
def add_folder():
    form = CreateFolderForm()
    form.responsible.choices = User.form_list()
    ...
    if form.validate_on_submit():
        ... 


还有一件事 - choices期望tuple,而您目前正在提供list;更新form_list

@staticmethod
def form_list():
    return [
        (theme.id, theme.label) for theme in Theme.query.all()
    ]