从会话数据填充选择选项的正确方法是什么? [英] What is the correct way to populate select choices from session data?

查看:164
本文介绍了从会话数据填充选择选项的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  

在用户登录时,我在会话中存储了一些变量,以便稍后用来填充字段。 from flask_wtf import表单
从wtforms导入SelectField $ b $来自瓶子导入会话
$ b $ class InstitutionForm(表单):
$ b $ city = session ['city']

city_tuples = [(x,x)for x in city]

organization = SelectField(
'organization',
choices = city_tuples


$ b $类别机构(视图):

方法= ['POST']

def dispatch_request(self):
$ b $ form = InstitutionForm()
return render_template(
form / institution.html',
form = form)

运行应用程序时,出现在请求上下文之外工作的错误。从会话数据填充此字段的正确方法是什么?

解决方案

类定义中的代码在导入时执行,不是当类被实例化时。您需要将访问权移动到 session __ init __ 方法中,以便在创建表单时访问(b

















$在session.get('city',('not set')中为x自定义__init __(self,* args,** kwargs):
self.organization.kwargs ['choices'] = [(x,x) ,))]
表单.__ init __(self,* args,** kwargs)

这适用于需要应用程序或请求上下文的任何内容,如数据库查询,而不仅仅是 session


I'm storing some variables in the session when the user logs in, to use later to populate a field.

from flask_wtf import Form
from wtforms import SelectField
from flask import session

class InstitutionForm(Form):

    city = session['city']

    city_tuples = [(x, x) for x in city]

    organisation = SelectField(
        'organisation',
        choices=city_tuples
    )


class Institution(View):

    methods = ['POST']

    def dispatch_request(self):

        form = InstitutionForm()
        return render_template(
            'form/institution.html',
            form=form)

When I run the app I get the error 'working outside of request context'. What is the correct way to populate this field from the session data?

解决方案

Code in a class definition is executed at import time, not when the class is instantiated. You need to move the access to session to the __init__ method so that it will be accessed when creating a form in a view function.

class Institution(Form):
    organization = SelectField()

    def __init__(self, *args, **kwargs):
        self.organization.kwargs['choices'] = [(x, x) for x in session.get('city', ('not set',))]
        Form.__init__(self, *args, **kwargs)

This applies to anything that needs an application or request context, such as a database query, not just the session.

这篇关于从会话数据填充选择选项的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆