簡體   English   中英

填充WTForms FormField FieldList,數據結果以字段形式顯示HTML

[英]Filling WTForms FormField FieldList with data results in HTML in fields

我有一個Flask應用程序,我可以通過上傳CSV文件填充表單數據然后讀取。 我想用從CSV讀取的數據填充FieldList。 但是,當我嘗試填充數據時,它會將原始HTML輸入到TextFields中,而不僅僅是我想要的值。 我究竟做錯了什么?

app.py

from flask import Flask, render_template, request, url_for
from flask.ext.wtf import Form
from wtforms import StringField, FieldList, FormField, SelectField
from wtforms.validators import DataRequired
from werkzeug.datastructures import MultiDict

app = Flask(__name__)
app.config['SECRET_KEY']='asdfjlkghdsf'

# normally student data is read in from a file uploaded, but for this demo we use dummy data
student_info=[("123","Bob Jones"),("234","Peter Johnson"),("345","Carly Everett"),
              ("456","Josephine Edgewood"),("567","Pat White"),("678","Jesse Black")]

class FileUploadForm(Form):
    pass

class StudentForm(Form):
    student_id = StringField('Student ID', validators = [DataRequired()])
    student_name = StringField('Student Name', validators = [DataRequired()])

class AddClassForm(Form):
    name = StringField('classname', validators=[DataRequired()])
    day = SelectField('classday', 
                      choices=[(1,"Monday"),(2,"Tuesday"),(3,"Wednesday"),(4,"Thursday"),(5,"Friday")],
                      coerce=int)

    students = FieldList(FormField(StudentForm), min_entries = 5) # show at least 5 blank fields by default

@app.route('/', methods=['GET', 'POST'])
def addclass():
    fileform = FileUploadForm()
    classform = AddClassForm()

    # Check which 'submit' button was called to validate the correct form
    if 'addclass' in request.form and classform.validate_on_submit():
        # Add class to DB - not relevant for this example.
        return redirect(url_for('addclass'))

    if 'upload' in request.form and fileform.validate_on_submit():
        # get the data file from the post - not relevant for this example.
        # overwrite the classform by populating it with values read from file
        classform = PopulateFormFromFile()
        return render_template('addclass.html', classform=classform)

    return render_template('addclass.html', fileform=fileform, classform=classform)

def PopulateFormFromFile():
    classform = AddClassForm()

    # normally we would read the file passed in as an argument and pull data out, 
    # but let's just use the dummy data from the top of this file, and some hardcoded values
    classform.name.data = "Super Awesome Class"
    classform.day.data = 4 # Thursday

    # pop off any blank fields already in student info
    while len(classform.students) > 0:
        classform.students.pop_entry()

    for student_id, name in student_info:
        # 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)

        classform.students.append_entry(studentform)

    return classform


if __name__ == '__main__':
    app.run(debug=True, port=5001)

模板/ addclass.html

<html>
    <head>
        <title>Flask FieldList Demo</title>
    </head>
    <body>
        <h1>Add Class</h1>
        {% if fileform %}
        <div>
            <p>Add class from file:</p>
            <form action="" method="post" enctype="multipart/form-data" name="fileform">
                {{ fileform.hidden_tag() }}
                <p><input type="submit" name="upload" value="Upload"></p>
            </form>
        </div>
        <hr>
        {% endif %}
        <div>
            <form action="" method="post" name="classform">
                {{ classform.hidden_tag() }}
                Class Name: {{ classform.name }}<br>
                Day: {{ classform.day }}<br>
                <br>
                <div>
                    <table>
                        <tr>
                            <th> Student Number </th>
                            <th> Name </th>
                        </tr>
                        {% for student in classform.students %}
                        <tr>
                            <td>{{ student.student_id }}</td>
                            <td>{{ student.student_name }}</td>
                        </tr>
                        {% endfor %}
                    </table>
                </div>
                <p><input type="submit" name="addclass" value="Add Class"></p>
            </form>
        </div>
    </body>
</html>

違規代碼段發生在classform.students.append_entry(studentform) 如果需要,我可以發布輸出HTML。 我的期望是這樣的: 預期產出 我得到的是: 在此輸入圖像描述

好吧,我花了好幾個小時,最后這是一個微不足道的代碼更改。

大多數字段允許您通過修改data屬性來更改其值(正如我上面所做的那樣)。 事實上,在我的代碼中,我有如上所述的評論:

    ### 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)

但是,對於FormFields的FieldList,我們不應該編輯data屬性,而應該編輯字段本身。 以下代碼按預期工作:

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)

我希望這有助於遇到同樣問題的人。

響應接受的答案:append_entry函數需要數據,而不是Form。 因此,如果您像這樣接近它,您的代碼也可以按照您的預期運行。 具有易於維護的額外好處

# 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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM