从数据库或会话数据填充字段的正确方法是什么? [英] What is the correct way to populate fields from database or session data?

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

问题描述

当用户登录时,我在会话中存储了一些变量,以供以后使用以填充字段.

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?

推荐答案

类定义中的代码在导入时执行,而不是在实例化该类时执行.您需要将对 session 的访问权限移至 __ init __ 方法,以便在视图函数中创建表单时可以对其进行访问.

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',))]
        super().__init__(*args, **kwargs)

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

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

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

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