我可以在字段构造函数之外设置StringField的默认值吗? [英] Can I set a StringField's default value outside the field constructor?

查看:217
本文介绍了我可以在字段构造函数之外设置StringField的默认值吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在构造字段时设置了默认值,则所有工作都将按预期进行:

If I set the default value during construction of the field, all works as expected:

my_field = StringField("My Field: ", default="default value", validators=[Optional(), Length(0, 255)])

但是,如果我尝试以编程方式进行设置,则该设置无效.我已经尝试通过修改__init__方法,如下所示:

However, if I try to set it programmatically, it has no effect. I've tried by modifying the __init__ method like so:

class MyForm(FlaskForm):
    my_field = StringField("My Field: ", validators=[Optional(), Length(0, 255)])

    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        self.my_field.default = "set default from init"  # doesn't work

这没有设置默认值.我该如何以编程方式执行此操作(因为该值基于数据库查询是动态的,并且如果在__init__之外执行此操作,则它不会获得最新的值)?

This does not set the default value. How can I do this programatically (because the value is dynamic based on a database query, and if I do this outside of __init__ then it does not get the most current value)?

我的requirements.txt中的相关版本:

Flask==0.12
Flask-WTF==0.14.2
WTForms==2.1

此外,如果重要的话,我正在运行Python 3.6.

Also, I'm running Python 3.6 if that matters.

或者,我可以使用一种解决方案,该解决方案使我能够在添加新记录时在初始表单加载时为此字段设置值数据(与构造函数中指定的默认值相同的行为),但是也使用相同的表单进行编辑,所以我不希望它更改在编辑时已经保存/存储的对象数据.

Alternatively, I'm fine with a solution that enables me to set the value data for this field on initial form load when adding a new record (same behavior as default value being specified in constructor) but this same form is also used for editing so I would not want it changing object data that is already saved/stored on edit.

推荐答案

您可以通过传递 FlaskForm formdata参数.

You can set initial values for fields by passing a MultiDict as FlaskForm's formdata argument.

from werkzeug.datastructures import MultiDict

class MyForm(FlaskForm):
    my_field = StringField("My Field: ", validators=[Optional(), Length(0, 255)])


form = MyForm(formdata=MultiDict({'my_field': 'Foo}))

这将在呈现表单时将my_field输入的值设置为"Foo",覆盖该字段的默认值.但是,您不希望在将表单回发到服务器时覆盖这些值,因此您需要在处理程序中检查request方法:

This will set the value of the my_field input to 'Foo' when the form is rendered, overriding the default value for the field. However you don't want to override the values when the form is posted back to the server, so you need to check the request method in your handler:

from flask import render_template, request
from werkzeug.datastructures import MultiDict

@app.route('/', methods=['GET', 'POST'])
def test():
    if request.method == 'GET':
        form = MyForm(formdata=MultiDict({'my_field': 'Foo'}))
    else:
        form = MyForm()
    if form.validate_on_submit():
        # do stuff
    return render_template(template, form=form)

这篇关于我可以在字段构造函数之外设置StringField的默认值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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