Pre-Populate an edit form with WTForms and Flask Pre-Populate an edit form with WTForms and Flask flask flask

Pre-Populate an edit form with WTForms and Flask


You can populate each field separately like this:

form = editPostForm(form)form.postTitle.data = postTitle_from_databaseform.postSubtitle.data = postSubtitle_from_database

or you can populate your form fields from a given object using process method:

process(formdata=None, obj=None, **kwargs)

Take form, object data, and keyword arg input and have the fields process them.

Parameters:

  • formdata – Used to pass data coming from the enduser, usually request.POST or equivalent.
  • obj – If formdata has no data for a field, the form will try to get it from the passed object.
  • **kwargs – If neither formdata or obj contains a value for a field, the form will assign the value of a matching keyword argument to the field, if provided.

Since BaseForm does not take its data at instantiation, you must call this to provide form data to the enclosed fields. Accessing the field’s data before calling process is not recommended.


I was able to pre-populate HTML input and textarea fields from a SQL database with Python and Jinja as follows:

1. Store relevant data from database in a variable:

    name = db.execute("""SELECT name FROM users WHERE id = :id""", id=session["user_id"])    about = db.execute("""SELECT about FROM users WHERE id = :id""", id=session["user_id"])

2. Render template (with render_template function) and pass in the relevant variables:

return render_template("edit.html", name = name, about = about)

3. Pass variables via jinja to html input and textarea elements. Index into the object that has been passed as follows:

For an input tag use the value attribute as below:

    <input type="text" class="form-control" name="name" value="{{ name[0]["name"] }}">

For a textarea element:

    <textarea class="form-control" name="about">{{ about[0]["about"] }}</textarea>