title: flask-wtf editing a model using wtform Form constructor: pre-filling the form
body: <p>I am reading the Flask Web Development book and came across this:</p>
  
  <pre><code>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)
  </code></pre>
  
  <p>Basically, when the form is not posted or doesn't validate, this copies over the data from the current user. Now reading up on wtforms, I read this about the <strong>init</strong> method on a form:</p>
  
  <pre><code>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.
  </code></pre>
  
  <p>So I guess that means that we could write this (the sample below is my own):</p>
  
  <pre><code>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)
  </code></pre>
  
  <p>I figure that this should fill the form instance from the database model on GET, and from POST data after post. Testing this, it seems to work.. </p>
  
  <p>Now my question: is this way of writing an edit view correct? Or should I copy everything over field by field, like in the book?</p>