【问题标题】:Flask Form with parameters带参数的烧瓶表单
【发布时间】:2020-01-01 18:06:21
【问题描述】:

我正在尝试用一个参数定义一个 Flask 表单。这是我的方法:

forms.py

class RegisterPatternForm(FlaskForm):
    cursorPatients = MongoClient('localhost:27017').myDb["coll"].find({"field1": self.myParam}).sort([("id", 1)])
    patientOpts = []
    for pt in cursorPatients:
        row = (str(pt.get("id")), "{} {}, {}".format(pt.get("surname1"), pt.get("surname2"), pt.get("name")))
        patientOpts.append(row)

    patients = SelectMultipleField('Select the patient', validators=[Optional()], choices=patientOpts)
    submit = SubmitField('Register')

    def __init__(self, myParam, *args, **kwargs):
        super(RegisterPatternForm, self).__init__(*args, **kwargs)
        self.myParam = myParam

routes.py

myParam = 5
form = RegisterPatternForm(myParam)

基本上,我想读取routes.py 上定义的变量myParam,格式为RegisterPatternFormroutes.py 中的参数插入有效,RegisterPatternForm 中的 __init__ 方法也有效。它失败的地方是读取以cursorPatients开头的行上的字段。

因此,我的问题是,我该如何解决这个问题才能在表单中读取myParam 值?

【问题讨论】:

    标签: python flask flask-wtforms


    【解决方案1】:

    关于问题。

    cursorPatients/patients/etc 是类级别的变量(static 变量)。这意味着您在此级别没有instanceproperties。粗略地说,您试图使用self 访问一个对象,但没有创建对象。

    如果我理解正确,您需要使用Form property 更改一些choices

    让我们尝试使用__init__ 更改选择:

    class RegisterPatternForm(FlaskForm):
        patients = SelectMultipleField('Select the patient',
                                       validators=[Optional()],
                                       choices=[('one', 'one')])
    
        def __init__(self, patients_choices: list = None, *args, **kwargs):
            super().__init__(*args, **kwargs)
            if patients_choices:
                self.patients.choices = patients_choices
    
    RegisterPatternForm()  # default choices - [('one', 'one')]
    RegisterPatternForm(patients_choices=[('two', 'two')])  # new choices
    

    如您所见,patients 的选择正在使用constructor 发生变化。所以在你的情况下应该是这样的:

    class RegisterPatternForm(FlaskForm):
        patients = SelectMultipleField('Select the patient',
                                       validators=[Optional()],
                                       choices=[])
    
        def __init__(self, myParam: int, *args, **kwargs):
            super().__init__(*args, **kwargs)
            self.myParam = myParam
            self.patients.choices = self._mongo_mock()
    
        def _mongo_mock(self) -> list:
            """
            db = MongoClient('localhost:27017').myDb["coll"]
            result = []
            for pt in db.find({"field1": self.myParam}).sort([("id", 1)]):
                blablabla....
            return result
            Just an example(I `mocked` mongo)
            """
            return [(str(i), str(i)) for i in range(self.myParam)]
    
    
    form1 = RegisterPatternForm(1)
    form2 = RegisterPatternForm(5)
    print(form1.patients.choices)  # [('0', '0')]
    print(form2.patients.choices)  # [('0', '0'), ('1', '1'), ('2', '2'), ('3', '3'), ('4', '4')]
    

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2019-03-01
      • 1970-01-01
      • 2013-07-26
      • 2023-03-02
      • 2023-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-07
      相关资源
      最近更新 更多