Python Flask form handling error - HTTP request

Hello All,

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)


1 Like

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

PS: Just had another look at the docs, an actually the default parameter also accepts a callable… so you might simply define the field like so:

def get_user_department():
    return int(session['isLogged']['usrDepartment'])


class UserForm(FlaskForm):

    departmentSelect = SelectField(
        'Department',
        # ...
        default=get_user_department,
    )

This will then also get called during the request cycle.

Hi M3g4p0p,

Thanks for the assistance it works.

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.