Filling WTForms FormField FieldList with data results in HTML in fields Filling WTForms FormField FieldList with data results in HTML in fields python python

Filling WTForms FormField FieldList with data results in HTML in fields


OK, I spent hours on this and in the end it was such a trivial code change.

Most fields let you change their value by modifying the data attribute (as I was doing above). In fact, in my code, I had this comment as above:

    ### either of these ways have the same end result.    #    # studentform = StudentForm()    # studentform.student_id.data = student_id    # studentform.student_name.data = name    #    ### OR    #    # student_data = MultiDict([('student_id',student_id), ('student_name',name)])    # studentform = StudentForm(student_data)

However, in the case of a FieldList of FormFields, we should not edit the data attribute, but rather the field itself. The following code works as expected:

for student_id, name in student_info:    studentform = StudentForm()    studentform.student_id = student_id     # not student_id.data    studentform.student_name = name    classform.students.append_entry(studentform)

I hope this helps someone experiencing the same problem.


In response to the accepted answer:The append_entry function expects data, not a Form. So if you approach it like this your code also works as you'd expect. With the added benefit of being easier to maintain

# First remap your list of tuples to a list of dictsstudents = [dict(zip(["student_id","student_name"], student)) for student in student_info]for student in students:    # Tell the form to add a new entry with the data we supply    classform.students.append_entry(student)