首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Flask和WTForms -如何让wtforms刷新选择数据

Flask和WTForms -如何让wtforms刷新选择数据
EN

Stack Overflow用户
提问于 2012-08-29 12:39:48
回答 2查看 7K关注 0票数 9

我使用的是最新版本的flask、wtforms和Flask-WTForms。

我有一个显示表单的页面,其中一个是带有名为"A“的选项的选择框。

当应用程序启动时,一切都很好。在另一个表单中,我添加了一个名为"B“的记录。

现在,我想要的表单应该有选项A和B的选择框,只有选项A可用。我必须终止uWSGI并重启以获得刷新数据的wtforms。

那么,我错过了什么?如何让wtforms刷新数据?

下面是如何创建表单,其中getAgencyList返回要添加到选择框中的选项列表。在另一个对话中,我添加了一个代理,代理列表应该会更新,而不必重新启动应用程序:

代码语言:javascript
复制
class createUser(Form):
    """
    Users are given a default password
    """
    first_name   = TextField()
    last_name    = TextField()
    email = TextField('Email', [validators.Length(min=6, max=120), validators.Email()])
    user_role = SelectField(u'User Role', choices=[('1', 'User'), ('2', 'Admin')])
    org_role = SelectField(u'User Role', choices=[('1', 'Agency'), ('2', 'Advertiser'),('3', 'Admin')])
    agency = SelectField(u'Agency', choices=getAgencyList())
EN

回答 2

Stack Overflow用户

发布于 2012-08-29 16:07:45

问题是getAgencyList()是在定义类时调用的。所以无论那个函数在那个时候返回什么,都是它的数据。为了更新列表信息,您必须在实例化期间以某种方式运行getAgencyList。为此,您可以使用关于wtforms的一个不太明显的事实,该事实允许您向特定字段添加选项。documentation is here只查找标题为“使用动态选择值选择字段”的小节。下面是一个应该可以工作的代码示例。

代码语言:javascript
复制
class CreateUserForm(Form):
    first_name = TextField()
    last_name = TextField()
    email = TextField('Email', 
            [validators.Length(min=6, max=120), validators.Email()])
    user_role = SelectField(u'User Role', 
            choices=[('1', 'User'), ('2', 'Admin')])
    org_role = SelectField(u'User Role', 
            choices=[('1', 'Agency'), ('2', 'Advertiser'),('3', 'Admin')])
    agency = SelectField(u'Agency')

    @classmethod
    def new(cls):
        # Instantiate the form
        form = cls()

        # Update the choices for the agency field
        form.agency.choices = getAgencyList()
        return form

# So in order to use you do this ...
@app.route('/someendpoint')
def some_flask_endpoint():
    # ... some code ...
    form = CreateUserForm.new()
    # That should give you a working CreateUserForm with updated values.
    # ... some more code to validate form probably...
票数 11
EN

Stack Overflow用户

发布于 2016-01-26 08:04:39

一个简单的解决方案是从数据库获取要显示的选项,然后用这些选项覆盖Form Class:

例如:

代码语言:javascript
复制
def get_agencies():
    agency_list = []
    # get the Agencies from the database - syntax here would be SQLAlchemy
    agencies = Agency.query.all()
    for a in agencies:
        # generate a new list of tuples
        agency_list.append((a.id,a.name))
    return agency_list

@app.route('/somewhere',methods=['POST'])
def somewhere():
    form = createUser()
    # overwrite the choices of the Form Class
    form.agency.choices = get_agencies()
    # here goes the rest of code - like form.validate_on_submit()
    ...
    return render_template('create_user.html', form=form)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12170995

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档