Skip to main content
 首页 » 编程设计

python之flask-wtf 使用 wtform 表单构造函数编辑模型 : pre-filling the form

2025年05月04日8zhujiabin

我正在阅读 Flask Web Development 一书并遇到了这个:

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 数据中填充。测试这个,它似乎工作..

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

请您参考如下方法:

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

如果你打开 Flask-WTF 的代码,你会看到它继承了 WTForms 的 SecureForm 类,并尝试加载 Werkzeug POST MultiDict(称为 formdata) 默认情况下(如果存在)。所以在你的 View 中加载你的表单是这样的:

form = PostForm(obj=post) 

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

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