将值传递给WTForms类

时间:2017-04-16 19:05:25

标签: python flask wtforms flask-wtforms

我有一个函数Groups.byorgid(arg1),它将获取特定组织的所有组。我之前在WTForms中使用过类似的代码,其函数并不需要指定arg,但我需要将orgid arg传递给此函数,以便表单可以填充其下拉列表。我应该怎么做呢?

WTForm类:

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]

调用表单的函数是:

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

我是否需要为InviteUser类创建方法?如果是这样,那应该是什么样的?

1 个答案:

答案 0 :(得分:0)

以下是如何动态添加字段的方法:

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

并将其用作

form = user_forms.create_invite_user_form(orgid)