Filling WTForms FormField FieldList with data results in HTML in fields

江枫思渺然 提交于 2019-11-28 17:17:37

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 dicts
students = [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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!