使用 Flask 和 WTForms 我怎么能有一个表,其中一些列是输入? [英] Using Flask and WTForms how can i have a table where some columns are inputs?

查看:28
本文介绍了使用 Flask 和 WTForms 我怎么能有一个表,其中一些列是输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力了解这是如何完成的,文档似乎没有多大帮助.

I'm struggling to see how this is done, and the documentation doesn't seem to help much.

我需要生成一个表格,行大小是可变的,但不是动态的(我在生成页面之前知道我需要多少行).

I need to generate a table, the row size will be variable, but not dynamic (i know how much rows i need before generating the page).

为了简单起见,让我们想象一个页面,你用一个整数对 n 次考试进行评分.

For the sake of simplicity lets imagine a page where you grade n exams with an integer.

我试过这个:

表格.

class InputInteger(Form):
    grade = IntegerField('Grade')

视图

@decorator..
def grade():
    form = InputInteger()
    names = student_list

    return render_template("grade.html", form=form, names=names)

模板

<table>
    <tr>
        <th>Name</th>
        <th>Grade</th>
    </tr>
    {% for name in names %}
    <tr>
        <td>
            {{name}}
        </td>
        <td>
            {{form.grade}}
        </td>
    </tr>
</table>

但是我如何读回输入的值?我如何区分属于谁的年级?

But how do i read back the inputed values? How do i distinguish who's grade that belongs too?

我很困惑,我读过有关 FieldList(FormField(IntegerField)) 的内容,但这不只是一个包含整数列表的字段吗?表格小部件怎么样,我需要吗?

Am fairly confused, i've read about FieldList(FormField(IntegerField)), but isn't that just one field with a list of integers? What about the Table Widget, do i need that?

请帮忙.

推荐答案

对于现在看到这个的人来说,OP 考虑 FieldLists 和 FormFields 是正确的.这是一个解决方案:

For anyone looking at this now, the OP was correct to think about FieldLists and FormFields. Here is a solution:

forms.py:

class GradeForm(FlaskForm):
    student = IntegerField('Student ID')
    grade = IntegerField('Grade')
    delete = BooleanField('Delete')

class GradeFormSet(FlaskForm):
    gradeset = FieldList(FormField(GradeForm), min_entries=0)

view.py:

def grade():
    # create a dict of student IDs and their initial grades (or None for now)
    init_merits = [dict(student=s.id, grade=None) for s in myStudentTable.query.all()]
    gradeform = GradeFormSet(gradeset=init_merits)
    if form.validate_on_submit():
        ...
        # meritforms.data['gradeset'] contains a list of dictionary values for further processing
        # check 'delete' == True to handle deletion of that student from your table
        ...
    return render_template('template.html', form=gradeform)

模板:

<table>
{% for merit in form.gradeset %}
    <tr>
        <td>{{ merit.placing(readonly=true) }} {{ merit.csrf_token }} {{ merit.hidden_tag() }}</td>
        <td>{{ merit.grade }}</td>
        <td>{{ merit.delete }}</td>
    </tr>
{% endfor %}
</table>

<input type="submit" name="finish" value="Save">
<input type="submit" name="cancel" value="Cancel">

这篇关于使用 Flask 和 WTForms 我怎么能有一个表,其中一些列是输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆