用数据填充WTForms FormField FieldList会在字段中产生HTML

亚伦·D

我有一个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)

templates / 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。我期望的是这样的:预期产量我得到的是:在此处输入图片说明

亚伦·D

好的,我花了几个小时来解决这个问题,最后这是一个微不足道的代码更改。

大多数字段都允许您通过修改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)

我希望这可以帮助遇到同样问题的人。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

嵌套的WTForms FieldList在字段中产生HTML

WTForm FormField填充值

无法使用wtforms,append_entry()和FieldList(FormField())更改动态添加的表单字段的标签

无法从validate_on_submit上的WTForms FormField取回数据

WTForms FormField 导致 csrf_token 错误

'fieldlist'/'FormField'无法使用flask_wtf正确呈现

如何动态设置WTForms FormField的默认值?

用值预填充wtforms文本字段

FormField.Add方法不会返回对新字段的引用(错误?)

用JSON数据填充HTML

在基于Django类的视图中从上下文数据设置初始formfield值

Odoo-用数据填充字段

用 json 数据填充 html 模板

Kendo UI FormField并排

用cv.glmnet并行设置种子会在R中产生不同的结果

用utf8插入ASCII会在open()中产生错误

用 R 中数据框中的日期填充字段

将两个数据框与left_join合并会在“ right”列中产生NA

使用额外的空格对文本文件中的数据进行排序会在 python 中产生错误

用jQuery填充HTML表数据失败未捕获ReferenceError

用svelte中的js数据填充html表

用 MySQL 数据填充 HTML 表的列和行

用 ViewModel 中的数据填充 @Html.DropDownListFor

Flask WTForms 如何返回 Posted FieldList 表单行数据

检查formfield是多行还是不使用itextsharp

Django 1.9不能将formfield留空

通过vba保存pdf之前更新formfield

将焦点设置为formField1

使用JSON格式的数据用JQuery AJAX填充HTML表:如何从变量中循环访问数据?