WT表格中的加入会话对象

时间:2013-09-22 01:37:49

标签: flask wtforms flask-wtforms

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

view.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"

文件“C:\ Users \ dell \ Envs \ surveyApp \ lib \ site-packages \ flask \ globals.py”,第20行,在_lookup_req_ob中 JECT     引发RuntimeError('在请求上下文之外工作') RuntimeError:在请求上下文之外工作

2 个答案:

答案 0 :(得分:1)

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

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)

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

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

希望它会对你有所帮助。

答案 1 :(得分: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文档中的SelectField from Dynamic Choices