Monday, 6 January 2020

Flask Form with parameters

I am trying to define a Flask form with one parameter. This was my approach:

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)

Basically, I want to read the variable myParam defined on routes.py on the form RegisterPatternForm. The insertion of the param in routes.py works, as well as the __init__ method in RegisterPatternForm. Where it fails is when reading the field on the line that starts with cursorPatients.

Therefore, my question is, how can I solve this problem in order to be able to read myParam value inside the form?



from Flask Form with parameters

No comments:

Post a Comment