3

我有一个简单的单选字段,它总是导致 validate_on_submit 返回 false。当我打印 form.errors 时,看起来“不是一个有效的选择”作为来自无线电字段的值被传递,尽管 coerce=int。

我认为我不会破坏表单中返回的任何内容,我希望以正确的方式创建动态选择。我不明白为什么这会失败。

这是我项目的相关部分 - 任何建议表示赞赏。

表格.py:

class SelectRecord(Form):
    rid = RadioField("Record Select", choices=[], coerce=int,validators=[InputRequired()])

视图.py:

@mod.route('/select/', methods=('GET', 'POST'))
@login_required
def select_view():
    form = SelectRecord(request.form)
    if form.validate_on_submit():
        rid = form.data.rid
        if form['btn'] == "checkout":
            # check out the requested record
            Records.checkoutRecord(rid)
            return render_template('/records/edit.html',rid=rid)
        elif form['btn'] == "checkin":
            Records.checkinRecord(rid)
            flash("Record checked in.")
    else:
        mychoices = []
        recs_co = session.query(Records.id).filter(Records.editing_uid == current_user.id).  \
            filter(Records.locked == True)
        for x in recs_co:
            mychoices.append((x.rid,"%s: %s (%s)" % (x.a, x.b, x.c, x.d)))
        x = getNextRecord()
        mychoices.append((x.id,"%s: %s (%s %s)" % (x.a, x.b, x.c, x.d)))
        form.rid.choices = mychoices
    print form.errors
    return render_template('records/select.html', form=form)

还有我的模板(select.html):

<form method="POST" action="/select/" class="form form-horizontal" name="select_view">
        <h1>Select a record to edit:</h1>
        {{ render_field(form.rid, class="form-control") }}
        {{ form.hidden_tag() }}
        <button type="submit" name="btn" class="btn" value="Check Out">Check Out</button>
        <button type="submit" name="btn" class="btn" value="Check In">Check In</button>
    </form>
4

1 回答 1

6

你的领域看起来像这样......

rid = RadioField("Record Select", choices=[], coerce=int,validators=[InputRequired()])

请注意,您将选择保留为空列表。你基本上是在说,“没有对这个领域有效的选择”。如果 WTForms 认为没有任何选择可供选择,那么您使用的选择将始终无效。

现在,您似乎正在尝试在 else 语句中添加这些选项...

form.rid.choices = mychoices

在运行时,您将能够正确呈现表单(这发生在您的方法结束时)。然而,时间安排使得选择表单对象的时间太晚,无法用作验证的一部分,因为这发生在方法的顶部附近validate_on_submit()

尝试使用您正在使用的代码来填写 form.rid.choices 并让它在您执行之前运行validate_on_submit

于 2013-11-24T02:31:44.857 回答