繁体   English   中英

validate_on_submit始终使用Flask WTForms返回false

[英]validate_on_submit always returns false using Flask WTForms

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

我不认为我正在破坏表格中返回的任何东西,我希望以正确的方式创造动态选择。 我不明白为什么会失败。

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

forms.py:

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

views.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>

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

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

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

现在,看起来你正在尝试在你的else语句中添加下面的选项......

form.rid.choices = mychoices

在运行时,您将能够正确呈现表单(在方法结束时发生)。 但是,时间是这样的,选择被赋予表单对象太晚,不能用作验证的一部分,因为这发生在validate_on_submit()方法的顶部附近!

尝试使用您使用的代码填充form.rid.choices,并在执行validate_on_submit之前运行它。

暂无
暂无

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

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