【问题标题】:flask-wtf editing a model using wtform Form constructor: pre-filling the formflask-wtf 使用 wtform 编辑模型表单构造函数:预填充表单
【发布时间】:2014-08-22 15:35:05
【问题描述】:

我正在阅读 Flask Web 开发这本书并遇到了这个问题:

def edit_profile():
    form = EditProfileForm()
    if form.validate_on_submit():
        current_user.name = form.name.data
        current_user.location = form.location.data
        current_user.about_me = form.about_me.data
        db.session.add(user)
        flash('Your profile has been updated.')
        return redirect(url_for('.user', username=current_user.username))
    form.name.data = current_user.name
    form.location.data = current_user.location
    form.about_me.data = current_user.about_me
    return render_template('edit_profile.html', form=form)

基本上,当表单未发布或未验证时,它会复制当前用户的数据。现在阅读 wtforms,我阅读了有关表单上的 init 方法的内容:

obj – If formdata is empty or not provided, this object is checked for attributes
      matching form field names, which will be used for field values.

所以我想这意味着我们可以写这个(下面的示例是我自己的):

def edit_post(post_id):
    post = Post.query.get_or_404(post_id)
    if current_user != post.author:
        abort(403)
    # Below is the line I am concerned about
    form = PostForm(formdata=request.form, obj=post)
    if form.validate_on_submit():
        form.populate_obj(post)
        db.session.commit()
        return redirect(url_for('user', username=current_user.username))
    return render_template('post_form.html', form=form)

我认为这应该在 GET 上从数据库模型中填充表单实例,并在发布后从 POST 数据中填充。测试一下,它似乎工作..

现在我的问题是:这种编写编辑视图的方式是否正确?还是应该像书中那样逐个字段地复制所有内容?

【问题讨论】:

    标签: python flask wtforms flask-wtforms


    【解决方案1】:

    在 POST MultiDict 中加载无疑是将键/值对映射到 WTForms 实例的公认方式。更重要的是,如果您使用的是 Flask-WTF 扩展程序,这会自动为您完成,这是该扩展程序为您带来的好处之一。

    如果你要破解 Flask-WTF 的代码,你会看到它继承了 WTForms 的 SecureForm 类,并在默认情况下尝试加载 Werkzeug POST MultiDict(称为 formdata)(如果存在) .因此,在您的视图中加载您的表单,如下所示:

    form = PostForm(obj=post)
    

    应该足够(如果使用 Flask-WTF)也可以用 POST 数据填充字段。

    在您的书示例中完成的方式当然没有错,但会创建许多不必要的代码并且容易出错/冗余 - 人们可能会忘记提及在 WTForms 实例中声明的视图中的字段。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-08
      • 2022-10-15
      相关资源
      最近更新 更多