【问题标题】:Using FieldList and FormField使用 FieldList 和 FormField
【发布时间】:2012-08-20 15:34:48
【问题描述】:

我们有以下表格,我们正在尝试为每个组创建GroupRoleForms 列表。

class FullNameMixIn():
    full_name = TextField(
        'Full name', [
            validators.required(message=u"Full name is required")
        ])

class GroupRoleForm(Form):
    group =BooleanField('Group', default=False)
    role = SelectField(
            'Role',choices=[
            ("none", "----------"), 
            ('approver', 'Approver'),
            ('editor', 'Editor')
            ])

class AdminEditUserForm(Form, FullNameMixIn):
    group_roles = FieldList(FormField(GroupRoleForm))

我们如何创建一个包含GroupRoleForms 预填充列表的AdminEditUserForm 实例?

目前我们正在尝试这样做:

form = forms.AdminEditUserForm()
for group in  company.groups:
    group_role_form = forms.GroupRoleForm()
    group_role_form.group.label =  group.name
    group_role_form.group.name = group.id
    form.group_roles.append_entry(group_role_form)
return dict(edit_user_form = form )

【问题讨论】:

  • 你有没有想过解决这个问题?如果你这样做了,请发布你的解决方案
  • 你想动态追加字段是吗?你知道 append_entry 没有得到 formdata。
  • 很简单,通过添加一个初始化函数,就可以做到这一点。
  • 我认为您的动态表单组合可能有点过头了。您只需将数据绑定到顶级表单对象即可达到预期效果,让 WTForms 完成工作。
  • 我在这里创建了一个完整的工作示例:github.com/sebkouba/dynamic-flask-form

标签: python wtforms


【解决方案1】:

说明

Formdataformdata 关键字参数中,您只需要一个带有key 的字典,该字典与包含可迭代的FieldList 子字段匹配。该可迭代需求中的项目又具有与FieldList 的字段列表匹配的属性的项目。

如果您遵循下面的示例,我会得到预先填充好的嵌套表单。

代码

from collections import namedtuple

from wtforms import validators
from wtforms import Form
from wtforms import SelectField
from wtforms import BooleanField
from wtforms import TextField
from wtforms import FieldList
from wtforms import FormField

from webob.multidict import MultiDict

# OP's Code
class FullNameMixIn():
    full_name = TextField(
        'Full name', [
            validators.required(message=u"Full name is required")
        ])

class GroupRoleForm(Form):
    group =BooleanField('Group', default=False)
    role = SelectField(
            'Role',choices=[
            ("none", "----------"), 
            ('approver', 'Approver'),
            ('editor', 'Editor')
            ])

class AdminEditUserForm(Form, FullNameMixIn):
    group_roles = FieldList(FormField(GroupRoleForm))

# create some groups
Group = namedtuple('Group', ['group', 'role'])
g1 = Group('group-1', 'none')
g2 = Group('group-2', 'none')

# drop them in a dictionary 
data_in={'group_roles': [g1, g2]}

# Build form 
test_form = AdminEditUserForm(data=MultiDict(data_in))

# test print
print test_form.group_roles()

呈现的 HTML(截断)

<ul id="group_roles">
   <li>
      <label for="group_roles-0">Group Roles-0</label> 
      <table id="group_roles-0">
         <tr>
            <th><label for="gr
               oup_roles-0-group">Group</label></th>
            <td><input checked id="group_roles-0-group" name="group_roles-0-group" type="checkbox" value="y"><
               /td>
         </tr>
         <tr>
            <th><label for="group_roles-0-role">Role</label></th>
            <td>
               <select id="group_roles-0-role" name="group_roles-0-role">
                  <option
                     selected value="none">----------</option>
                  <option value="approver">Approver</option>
                  <option value="editor">Editor</option>
               </select>
            </td
               >
         </tr>
      </table>
   </li>
   <li>
      <label for="group_roles-1">Group Roles-1</label> 
      <table id="group_roles-1">
         <tr>
            <th><label for="group_roles-1-gro
               up">Group</label></th>
            <td><input checked id="group_roles-1-group" name="group_roles-1-group" type="checkbox" value="y"></td>
         </tr>
         <tr>
            <t
               h>
            <label for="group_roles-1-role">Role</label></th>
            <td>
               <select id="group_roles-1-role" name="group_roles-1-role">
                  <option selected value
                     ="none">----------</option>
                  <option value="approver">Approver</option>
                  <option value="editor">Editor</option>
               </select>
            </td>
         </tr>
      </table>
      <
      /li>
</ul>

...

【讨论】:

  • 有趣的 WTForms 说由于 html 限制,您不能在 FieldLists 中使用布尔字段,没有检查您的示例,但要小心。
  • mreh 仍然适用于所有其他字段类型。 SubmitField 不工作的原因很明显。 BooleanField 编码表单时必须失败,但它可能非常微妙(取最后一个复选框的值或其他东西)
  • 最近我找到了这个答案。根据对我有用的方法,我认为关于布尔和提交字段的 FieldList 限制确实直接适用于这些字段,但不适用于 FormField 中包含的子表单。 Form(data=...) 中的 data 参数也不需要是 MultiDict,标准 dict 即可。
  • @VPfB - 这是真的。你可以只使用FieldList(FormField(MyFormWithBooleanFields)),它工作正常。
【解决方案2】:

我不熟悉这些包,但我会尝试一下:

class AdminEditUserForm(Form, FullNameMixIn):
    def __init__(self, groups):
        super(AdminEditUserForm, self).__init__()
        self.group_roles = FieldList(FormField(GroupRoleForm))
        for group in groups:
            self.group.label = group.name
            self.group.name = group.id
            self.group_roles.append_entry(self.group)  
            # If this doesn't create a copy of the GroupRoleForm 
            # superclass in group_roles, then you need a method to do it
            self.__clear_group()

    def __clear_group(self):
        # copy GroupRoleForm object, if needed
        # delete GroupRoleForm object
        ...

那么你可以这样称呼它:

form = forms.AdminEditUserForm(company.groups)

【讨论】:

    猜你喜欢
    • 2019-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多