Python:SelectField“不是一个有效的选择”

时间:2017-04-25 07:42:30

标签: python flask wtforms flask-wtforms

form.py

class Confirm(CSRFForm):
    monitor_updates = SelectField(
        lazy_gettext("Monitor updates of an app"),
        validators=[validators.Optional()], choices=[], coerce=int
    )

view.py

def upload_confirm():
    form = Confirm()

    if form.validate_on_submit:
        if form.monitor_updates.data == 0:
            current_workflow.installation_source.monitor_updates_id = None
            db.session.commit()
        else:
            current_workflow.installation_source.monitor_updates_id = form.monitor_updates.data
            db.session.commit()

    choices = [(app[1][0], app[1][1]) for app in list_choices]
    form.monitor_updates.choices =[(0, "Nothing matches")]
    form.monitor_updates.choices += choices

models.py

class InstallationSource(db.Model):

    monitor_updates_id = db.Column(db.Integer, db.ForeignKey('updates_software.id'))

填写表单并在下拉列表中选择“Nothing matches”时,值为0,我收到错误。

screenshot

如果选择其他值,则保存正确。 我只能使用数字0,因为所有其他数字都可以被占用

1 个答案:

答案 0 :(得分:2)

您需要选择逻辑

    choices = [(app[1][0], app[1][1]) for app in list_choices]
    form.monitor_updates.choices =[(0, "Nothing matches")]
    form.monitor_updates.choices += choices

来到form.validate_on_submit()方法之前:

def upload_confirm():
    form = Confirm()

    choices = [(app[1][0], app[1][1]) for app in list_choices]
    form.monitor_updates.choices =[(0, "Nothing matches")]
    form.monitor_updates.choices += choices

    if form.validate_on_submit():
        if form.monitor_updates.data == 0:
            current_workflow.installation_source.monitor_updates_id = None
            db.session.commit()
        else:
            current_workflow.installation_source.monitor_updates_id = form.monitor_updates.data
            db.session.commit()