无法在validate_on_submit上从WTForms FormField获取数据

时间:2017-02-19 13:22:12

标签: flask wtforms flask-wtforms

user_edit_profile.html:

{% extends "base.html" %}
{% import "bootstrap/wtf.html" as wtf %}
{% block mainbody %}
    <div class="container">
        <div class="col-md-8 col-md-offset-2">
            <div class="page-header">
                <h3>{{ _('User Edit Profile') }}</h3>
            </div>
            <div>
                {{ wtf.quick_form(form, form_type="horizontal", horizontal_columns=('md', 3, 9)) }}
            </div>
        </div>
    </div>
{% endblock %}

forms.py

from flask_wtf import FlaskForm
from wtforms import Form
class UserBasicInfoForm(Form):
    surname = StringField(lazy_gettext("Surname"), validators=[Length(0, 64)])

class UserEditProfileForm(FlaskForm):
    basic_information = FormField(UserBasicInfoForm)
    submit = SubmitField(lazy_gettext("Submit"), id="user_edit_profile_submit")

user.py

@user.route("/edit-profile", methods=["GET", "POST"])
@login_required
def edit_profile():
    form = UserEditProfileForm()
    form.basic_information.surname.data = current_user.surname
    if form.validate_on_submit():
        current_user.surname = form.basic_information.surname.data
        print(form.basic_information.surname.data)
        current_user.save()
        return redirect(url_for("frontend.index"))
    return render_template("user_edit_profile.html", form=form)

我没有粘贴models.py,因为它运行良好,我认为没有问题。

现在,print(form.basic_information.surname.data)反馈None,这意味着我无法从wtf表单中surname字段的输入中获得任何内容。

当我使用Charles捕获数据包时,我发现客户端确实已将输入内容(例如“Smith”)发送到服务器。但显然服务器丢失了它。

我还尝试在子表单中使用FlaskForm而不是Form,同时使用以下内容覆盖csrf_enabled args到False

def __init__(self, *args, **kwargs):
    kwargs['csrf_enabled'] = False
    FlaskForm.__init__(self, *args, **kwargs)

但这没有帮助。

我不知道问题出在哪里,谢谢你的帮助!

1 个答案:

答案 0 :(得分:0)

此问题的原因是订单,一开始,您的$autoload['helper'] = array('url'); current_user.surname,您写的是:

None

因此,您的form.basic_information.surname.data = current_user.surname form.basic_information.surname.data,同时覆盖了表单数据None

正确的顺序是这样的:

form.basic_information.surname.data