Filling WTForms FormField FieldList with data results in HTML in fields

后端 未结 2 1471
花落未央
花落未央 2020-12-04 17:18

I have a Flask app in which I can populate form data by uploading a CSV file which is then read. I want to populate a FieldList with the data read from the CSV. However, whe

相关标签:
2条回答
  • 2020-12-04 17:30

    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.

    0 讨论(0)
  • 2020-12-04 17:47

    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)
    
    0 讨论(0)
提交回复
热议问题