Reputation: 1947
I am trying to populate roles depending updon the id of organization, but seems that WT forms doesn't support session
@users.route('/', methods=['GET', 'POST'])
@users.route('/manage', methods=['GET', 'POST'])
@login_required
def manage_users():
form = User_Form()
return render_template('account/manage_users.html', form=form)
from flask import session
from wtforms import Form, SelectField, TextField, PasswordField, validators
class User_Form(Form, session):
username = TextField('Username', [validators.Length(min=4, max=25)])
password = PasswordField('New Password', [
validators.Required(),
validators.EqualTo('confirm', message='Passwords must match')
])
confirm = PasswordField(u'Repeat Password')
email = TextField(u'Email', [validators.Length(min=6, max=35)])
active = SelectField(u'Active', choices=[('1', 'True'), ('0', 'False')])
organization_id = session['user_id']
#role = "list roles according to organization_id"
File "C:\Users\dell\Envs\surveyApp\lib\site-packages\flask\globals.py", line 20, in _lookup_req_ob ject raise RuntimeError('working outside of request context') RuntimeError: working outside of request context
Upvotes: 0
Views: 489
Reputation: 16336
The trick here is to set the choices based on logic in the view.:
def manage_users():
form = User_Form()
if session['user_id'] == 1:
form.role.choices = [('Role1', 'Label1'), ('Role2', 'Label2')]
else:
form.role.choices = [...]
if form.validate():
...
return render_template('account/manage_users.html', form=form)
As long as the choices are set before validate()
is called, then you can change them how you see fit.
For reference see SelectField from Dynamic Choices in the WTForms docs.
Upvotes: 1
Reputation: 2476
As blender told, you can't use session in that way. Only way I can think of is use session in views and send necessary data while rendering template.
view.py
@users.route('/', methods=['GET', 'POST'])
@users.route('/manage', methods=['GET', 'POST'])
@login_required
def manage_users():
form = User_Form()
form.organization_id.data = session['user_id']
return render_template('account/manage_users.html', form=form)
And mark 'organization_id' as TextField in forms:
class User_Form(Form, session):
# Other fields
organization_id = TextField()
Hope it will help you.
Upvotes: 1