WTForms /烧瓶:动态min_entries

时间:2019-03-01 20:10:16

标签: python flask dynamic parameters wtforms

我希望动态使用min_entries WTForms参数,即不对数字进行硬编码。

在form.py中看起来像这样:

class TestSpecForm(FlaskForm): 
    student_number = IntegerField('Number of Students')


class StudentForm(FlaskForm):
    answer = StringField('')


class TestInputForm(FlaskForm):
    students = FieldList(FormField(StudentForm))  # I'd like to insert the dynamic min_entries here
    submit = SubmitField('Submit')

以及views.py中的类似内容:

def input(key_id):
    key = Testspecs.query.get_or_404(key_id) 
    student_number = key.student_number
    form = TestInputForm()
    form.students.min_entries = student_number
    if form.validate_on_submit():
        ...

但是,这不起作用,仅为TestInputForm呈现NO FIELDS。如果我将“ min_entries = 10”放入TestInputForm的students变量中,一切都会按预期进行。但是我不能动态完成它。

有人可以帮我吗?根据我所有的google / reddit / SO搜索,基本上这是动态设置WTForms中的大多数参数或验证器的方式。

谢谢

2 个答案:

答案 0 :(得分:1)

我刚刚发现了“字段列表”和“表单字段”,并在Internet上搜索了文档或示例,却几乎找不到帮助。我想出了一种在渲染模板时获取动态条目数的好方法,因此,我想在这里提交它以防万一。请注意,这不能解决使用按钮或类似方法即时添加条目的问题。

def input(key_id):
    key = Testspecs.query.get_or_404(key_id) 
    student_number = key.student_number
    form = TestInputForm()
    # if the form was submitted, then it will collect all the entries for us
    if form.validate_on_submit():
        # form has whatever entries were just submitted
        for entry in form.students.entries:
            ...
        return(redirect(...))
    # if we get here, either validation failed or we're just loading the page
    # we can use append_entry to add up to the total number we want, if necessary
    for i in range(len(form.students.entries), student_number):
        form.students.append_entry()
    return render_template("input.html", form=form)

答案 1 :(得分:0)

无法在min_entries上动态覆盖FieldList

解决方法是将表单子类化,并用所需的值绑定新的FieldList

所以您的代码必须看起来像这样:

def input(key_id):
    key = Testspecs.query.get_or_404(key_id) 
    student_number = key.student_number
    # Subclass form and bind new field
    class LocalForm(TestInputForm):pass
    LocalForm.students = FieldList(FormField(StudentForm), min_entries=student_number)
    # Use our new form
    form = LocalForm()
    if form.validate_on_submit():
        ...