【发布时间】: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