What is the correct way to populate select choices from session data?

后端 未结 1 1217
一整个雨季
一整个雨季 2021-01-07 12:20

I\'m storing some variables in the session when the user logs in, to use later to populate a field.

from flask_wtf import Form
from wtforms import SelectFiel         


        
相关标签:
1条回答
  • 2021-01-07 13:02

    Code in a class definition is executed at import time, not when the class is instantiated. You need to move the access to session to the __init__ method so that it will be accessed when creating a form in a view function.

    class Institution(Form):
        organization = SelectField()
    
        def __init__(self, *args, **kwargs):
            self.organization.kwargs['choices'] = [(x, x) for x in session.get('city', ('not set',))]
            super().__init__(*args, **kwargs)
    

    This applies to anything that needs an application or request context, such as a database query, not just the session.

    0 讨论(0)
提交回复
热议问题