17

We have the following forms and we are trying to create list of GroupRoleForms for each group.

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))

How can we create a AdminEditUserForm instance that contains a pre-populated list of GroupRoleForms?

At the moment we are trying to do it this way:

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 )
5
  • did you ever get around to solving this? if you did, please post your solution
    – bool.dev
    Mar 23, 2013 at 7:49
  • do you want to append fields dynamically is that it? you know that append_entry doesn't get formdata.
    – dza
    Aug 20, 2013 at 15:03
  • Simple, by adding an init function, that does exactly that. Sep 23, 2013 at 7:58
  • I think your dynamic form composition might be overdoing it a bit. You can achieve the desired effect by just binding your data to the top-level form object, letting WTForms do the work.
    – nsfyn55
    May 30, 2014 at 17:54
  • I've created a full working example here: github.com/sebkouba/dynamic-flask-form
    – SebK
    Jan 3, 2016 at 7:09

2 Answers 2

8

Explanation

In your data or formdata keyword arguments for the Form you just need an dictionary with a key that matches the FieldList subfield that contains an iterable. The items in that iterable need in turn have items w/ attributes that match with FieldList's list of fields.

If you follow the example below I get nested Forms that are pre-populated just fine.

The Code

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()

The Rendered HTML(Truncated)

<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>

...
4
  • Interesting enough WTForms says that you cannot use boolean fields in FieldLists due to html limitation, didn't check your sample but be careful. May 22, 2015 at 11:51
  • mreh still holds true for all other field types. SubmitField doesn't work for obvious reasons. BooleanField must fail when encoding the form, but its likely very subtle(takes the value of the last checkbox or something)
    – nsfyn55
    May 22, 2015 at 16:56
  • 2
    Recently I found this answer. Based on what works for me, I think the FieldList limitation regarding boolean & submit fields does apply directly to these fields, but not to subforms included with FormField. Also the data argument in Form(data=...) does not need to be a MultiDict, a standard dict will do.
    – VPfB
    Jan 2, 2017 at 8:42
  • @VPfB - This is true. You could just have FieldList(FormField(MyFormWithBooleanFields)) and it works fine.
    – Neil
    Jun 6, 2020 at 17:25
1

I'm not familiar with these packages but I'll take a stab:

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
        ...

then you can call it like so:

form = forms.AdminEditUserForm(company.groups)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.