I’m trying to assign a value from the session that I created in the login script to set as a default value in the form handling class in this case the department value. As of now the default value of a dropdown menu list is hard coded and I like to assign the value stored in the session.
Error message received:
This typically means that you attempted to use functionality that needed an active HTTP request. Consult the documentation on testing for information about how to avoid this problem.
inputForm1.py
// testDepartmentValue assigned the session variable department
testDepartmentValue = int(session["isLogged"]['usrDepartment'])
//Current:
class UserForm(FlaskForm):
departmentSelect = SelectField('Department', coerce=str, choices=[(dpt.dpt_index, dpt.dpt_display) for dpt in dbQueryDepartment], default = 3)
//Objective:
// I like to assign the department value from the session as the default value in the dropdown list menu
class InputForm(FlaskForm):
departmentSelect = SelectField('Department', coerce=str, choices=[(dpt.dpt_index, dpt.dpt_display) for dpt in dbQueryDepartment], default = testDepartmentValue)
Hi @robin01, this would indeed only run once at application startup when there is no session yet, not while processing a request. A dynamic default could however be achieved by subclassing the select widget and adding a default property descriptor, where the getter would then be called each time the field is getting processed… along the following lines:
class DepartmentSelectField(SelectField):
_default = None
@property
def default(self):
return session.get('department', self._default)
@default.setter
def default(self, value):
self._default = value
Glad I could help… BTW you should probably populate the choices dynamically likewise; otherwise updating the departments in the database will only get reflected in the forms after application restart.