Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
563 views
in Technique[技术] by (71.8m points)

python - What is the correct way to populate fields from database or session data?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...