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
<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>
我的目标是使用灵活数量的条目创建表单init,例如链接中显示的示例。每当我运行我的代码时,我都会收到以下错误:
TypeError: 'UnboundField' object is not callable
当我注释掉 init 函数时,除了非灵活的图书字段数量外,表单按预期工作。我花了很长时间寻找答案,但无法找到解决问题的方法。
任何帮助都是预先确定的!
答案 0 :(得分:1)
这不是理想的解决方案,但这有效。
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)