将先前表单中定义的变量传递给另一个表单

Passing a variable defined in previous form to another form

所以我正在制作这个烧瓶应用程序,我需要一些关于变量访问的帮助。

大多数时候,当您在 Flask 中定义一个表单时,您将执行以下操作:

class MyForm(Form):
    my_field = StringField('I'm a field')
    my_submit = SubmitField('Go!')

当您需要表单的时候,您将使用 form = MyForm()

声明 class 的实例

到目前为止,一切都很好,但是:

如果您想说 SelectField(下拉菜单),其中的选择取决于先前表格的答案,您需要能够为新表格提供这些选择。这就是我想要实现的目标,但我无法获得一个变量来保存其内容。

这是我的表单代码(页面代码之上):

class DataMappingForm(Form):

    dm_choices = #I need this array !

    DMpatient_id = SelectField(u'Select Patient ID Column', 
            choices=dm_choices, validators=[Required()])
    ...

这是我的页面代码:

@app.route('/upload', methods=['GET','POST'])
def upload():
    uform = SomeOtherForm()
    if uform.is_submitted() and uform.data['Usubmit']:
        #Do stuff from previous form
        # and declare array_of_choices
    dmform = DataMappingForm() #Needs array_of_choices to work
    ...

到目前为止我尝试过的内容:

我应该提一下,这一切都需要在同一页上。

有没有办法将这个 array_of_choices 传递给我的 DataMappingForm class ?

编辑 这是我尝试 __init__ 重载时的样子:

class DataMappingForm(Form):
     def __init__(self, dm_choices, *args, **kwargs):
         self.dm_choices = dm_choices
         Form.__init__(self, *args, **kwargs)

     DMpatient_id = SelectField(u'Select Patient ID Column', 
             choices=dm_choices, validators=[Required()])
#I've tried putting it above or below, I get 'dm_choices is not defined'

我明白了!感谢@synonym 用你最后的 link.

为我指明了正确的方向

您需要做的就是声明一个定义了 class 的函数。然后将变量传递给函数,它将在 class.

中访问

最后,使函数 return 成为表单对象。

示例:

def makeMyForm(myArray):
    def class MyForm(Form):
        my_select_field = SelectField(u'I'm a select field', choices=myArray)
        my_submit = SubmitField(u'Go!')
    return MyForm()

要制作表格,您可以使用:

form = makeMyForm(theArrayYouWant)

瞧!

注意:由于我之前遇到过这个问题,我会提到 Array 由元组组成:

myArray = [('value','What you see'),('value2','What you see again')]

如果您想动态更改 SelectField 的选择,以下应该可行:

class DataMappingForm(Form):

    def __init__(self, choices)
        self.DMpatient_id.choices = choices

    DMpatient_id = SelectField(u'Select Patient ID Column') #note that choices is absent

如果您想要完全动态的字段,您可以在函数中动态创建 class。来自 WTForms Documentation:

def my_view():
    class F(MyBaseForm):
        pass

    F.username = StringField('username')
    for name in iterate_some_model_dynamically():
        setattr(F, name, StringField(name.title()))

    form = F(request.POST, ...)
    # do view stuff

在这种情况下,您可以根据需要自定义表单。当然,如果您只想自定义选项,第一种方法就足够了。