0

我正在尝试根据组织的 ID 填充角色,但似乎 WT 表单不支持会话

视图.py

@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)

user_form.py

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"

_lookup_req_object 中的文件“C:\Users\dell\Envs\surveyApp\lib\site-packages\flask\globals.py”,第 20 行引发 RuntimeError('working outside of request context') RuntimeError: working outside of request context

4

2 回答 2

1

这里的技巧是根据视图中的逻辑设置选择。:

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)

只要在validate()调用之前设置了选项,您就可以按照您认为合适的方式更改它们。

有关参考,请参阅 WTForms 文档中Dynamic Choices 中的 SelectField 。

于 2013-09-23T17:06:44.010 回答
1

正如搅拌机所说,您不能以这种方式使用会话。我能想到的唯一方法是在视图中使用会话并在渲染模板时发送必要的数据。

视图.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)

并在表单中将“organization_id”标记为 TextField:

class User_Form(Form, session):
    # Other fields
    organization_id = TextField()

希望它会帮助你。

于 2013-09-23T05:47:04.343 回答