当在视图函数中修改表单字段的属性时,validate_on_submit 在 POST 上失败

validate_on_submit fails on POST when attributes of form fields modified in view function

我有一个简单的 wtforms.RadioField 来接受用户在我的应用程序中定义的表单中的选择:

class VoteForm(FlaskForm):
    vote_option = RadioField("Choices", coerce=int)
    submit = SubmitField('Submit')

而我的视图函数是:

@main.route('/poll/<poll_id>/vote', methods=["GET", "POST"])
def vote(poll_id):
    poll = Poll.query.filter_by(id=poll_id).first()
    form = VoteForm()
    form.vote_option.choices = [(o.id, o.option) for o in poll.options]
    form.vote_option.default = poll.options[0].id
    form.process()

    if form.validate_on_submit():
        print(form.vote_option.data)

    return render_template("vote.html", form=form)

模板很简单:

{% extends "base.html" %}
{% import "bootstrap/form.html" as wtf %}

{% block page_content %}
    {{ wtf.render_form(form) }}
{% endblock %}

但是,当我从表单 post 时,它没有经过验证,控制台也没有打印任何内容。

如果我改为在视图函数中删除对表单的修改并将 vote_option 字段定义为:

vote_option = RadioField("Choices", choices=[("ONE", "ONE"), ("TWO", "TWO")])

可以按预期验证表单。在视图函数中修改窗体的属性是怎么回事?

在视图函数中删除对 form.process() 的调用解决了问题。虽然我不完全确定为什么。我会接受一个可以解释原因的答案。