RyanH
RyanH

Reputation: 1051

Passing a Value to a WTForms Class

I have a function Groups.byorgid(arg1) which will get all of the groups of a particular organization. I've used similar code before in WTForms with functions that didn't require specifying an arg, but I need to pass on the orgid arg to this function so that the form can populate its dropdown. How should I go about doing that?

WTForm Class:

class InviteUser(Form):
    ''' Allows an org to invite a user '''
    groups = Groups.byorgid(orgid)
    group = SelectField(
                        coerce=int,
                        choices=[(g.id, g.name) for g in groups]

The function calling the form is this:

def invite_user():
    orgid = current_user.orguser().Organizations.id
    form = user_forms.InviteUser()

Do I need to create a method for the class InviteUser? If so, what should that look like?

Upvotes: 0

Views: 1010

Answers (1)

Pavel Vergeev
Pavel Vergeev

Reputation: 3380

Here's how you can dynamically add the field:

def create_invite_user_form(orgid):
    class InviteUser(Form):
        pass
    groups = Groups.byorgid(orgid)
    group = SelectField(coerce=int, choices=[(g.id, g.name) for g in groups])
    setattr(InviteUser, "group", group)
return InviteUser()

And use it as

form = user_forms.create_invite_user_form(orgid)

Upvotes: 1

Related Questions