Flask wtforms-无法调用"UnboundField"对象,动态字段无法正确初始化 [英] Flask wtforms - 'UnboundField' object is not callable, dynamic field won't init properly

查看:288
本文介绍了Flask wtforms-无法调用"UnboundField"对象,动态字段无法正确初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

app.py

from flask import Flask, render_template
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, FieldList, FormField

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


class BookForm(FlaskForm):
    book = StringField('book title')


class LibraryForm(FlaskForm):
    def __init__(self, min_entries=0, *args, **kwargs):
        super(LibraryForm, self).__init__(*args, **kwargs)
        self.books = FieldList(FormField(BookForm), min_entries=min_entries)

    library = StringField('Library name')
    books = FieldList(FormField(BookForm), min_entries=3)
    submit = SubmitField('Submit')


@app.route('/book', methods=['GET', 'POST'])
def book():
    form = LibraryForm(min_entries=5)
    if form.validate_on_submit():
        return 'aww yeah'
    return render_template('books.html', form=form)

books.html

books.html

<html>
<form method="POST" action="">
    {{ form.hidden_tag() }}
    <div>{{ form.library.label }}: {{ form.library() }}</div>
    <div>{{ form.books.label }}: {{ form.books() }}</div>
    <div>{{ form.submit.label }}: {{ form.submit() }}</div>
</html>

我的目标是使表单具有灵活的条目数,例如链接中所示的示例.每当我运行代码时,都会出现以下错误:

My goal is to make my form init with a flexible number of entries, such as in the example shown in the link. Whenever I run my code I get the following error:

TypeError: 'UnboundField' object is not callable

当我注释掉 init 函数时,该表格可以正常工作,除了书本字段的数量不灵活.我花了很多时间寻找答案,但是找不到解决问题的方法.

When I comment out the init function, the form works as expected, apart from the non-flexible amount of Book Fields. I've spent quite some time looking for answers, but couldn't find any which solved the problem.

其外观示例

感谢您的帮助!

推荐答案

这不是理想的解决方案,但是可以.

It's not the ideal solution, but this works though.

from flask import Flask, render_template
from flask_wtf import FlaskForm, Form
from wtforms import StringField, SubmitField, FieldList, FormField

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


class BookForm(FlaskForm):
    book = StringField('book title')


class LibraryForm(FlaskForm):
    library = StringField('Library name')
    books = FieldList(FormField(BookForm))
    submit = SubmitField('Submit')


@app.route('/book', methods=['GET', 'POST'])
def book():
    form = LibraryForm()
    if form.validate_on_submit():
        return 'aww yeah'
    for i in range(6):
        form.books.append_entry()

    return render_template('books.html', form = form)

这篇关于Flask wtforms-无法调用"UnboundField"对象,动态字段无法正确初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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