Python Flask WTForms-数据库中的动态布尔字段

Python Flask WTForms-数据库中的动态布尔字段,python,flask,wtforms,Python,Flask,Wtforms,在我的flask项目中,我有views.py、models.py(SQLAlchemy to postgres)和forms.py文件。我一直在form.py中定义表单,并从views.py中实例化它们 我能够为SelectField创建动态内容,但在BooleanField中很难做到这一点。以下是我试图做的: 创建一个从团队中检索球员的表单(以db为单位)。为每个玩家创建一个布尔场。如果数据库中的“活动”字段为1,则该值为选中状态(true),否则为未选中状态(false)。系统用户可以选中/

在我的flask项目中,我有views.py、models.py(SQLAlchemy to postgres)和forms.py文件。我一直在form.py中定义表单,并从views.py中实例化它们

我能够为SelectField创建动态内容,但在BooleanField中很难做到这一点。以下是我试图做的:

创建一个从团队中检索球员的表单(以db为单位)。为每个玩家创建一个布尔场。如果数据库中的“活动”字段为1,则该值为选中状态(true),否则为未选中状态(false)。系统用户可以选中/取消选中任何框,然后提交表单

我迭代玩家没有问题,但我似乎不知道如何为每个BooleanField生成唯一的名称(如果他们有相同的名称,我将只返回一个值)。我还需要根据用户的活动状态动态传递默认值

我做了一些研究,并看到了一些关于匹配我的一个ORM模型的想法——但我并没有真正尝试创建一个字段条目来匹配我的玩家在ORM模型中的每一列——只是尝试提取一些数据并动态创建一个表单

也许可以在jinja2模板中完成这一切,但这似乎不是最好的方法

好的-现在正在尝试获取更基本的内容,但仍然存在问题-BooleanField始终返回False:

forms.py:

class myform(Form):
    available = BooleanField('available')
    submit = SubmitField('Save')
views.py:

form = myform(available=True)
webpage.html

Available: {{ form.available }}
当网页呈现时,复选框被选中(由于available=True),我正在传递该复选框,但当我提交时,该值返回为False)

我确实注意到奇怪的是,即使选中该框,呈现的HTML-


选中“”对我来说没有意义。我注意到,当我删除'available=True'时,没有选中的=“”。我认为应该检查正确的HTML=checked..

如果要根据表中特定列的值动态设置
布尔字段的
checked
属性,可以采用以下方法:

forms.py

# Create the boolean field in the form
is_active = BooleanField('Is Active')
# Select the players from the database and for each of them set the boolean field state
# Here we are selecting all players and iterating through them
# session.query() is specific to SQLAlchemy which is primarily used with flask as an ORM
players = session.query(Player).all()
for player in players:
  # Set other form fields like a dynamically populated SelectField etc.

  # Set the boolean field for each player here
  form.is_active.default = "checked" if player.active == 1 else ""
views.py

# Create the boolean field in the form
is_active = BooleanField('Is Active')
# Select the players from the database and for each of them set the boolean field state
# Here we are selecting all players and iterating through them
# session.query() is specific to SQLAlchemy which is primarily used with flask as an ORM
players = session.query(Player).all()
for player in players:
  # Set other form fields like a dynamically populated SelectField etc.

  # Set the boolean field for each player here
  form.is_active.default = "checked" if player.active == 1 else ""

让基础工作起来——工作太晚了,我只是在html中的表单标题下没有Boolean字段。仍在尝试动态执行此操作。如果form.available变为False,这意味着需要在视图中更改它并传递给响应,最好打印所有view.py代码