Flask WTForms autofill StringField with variable

不想你离开。 提交于 2019-12-06 07:37:35

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

from werkzeug.datastructures import MultiDict

form = NewForm(formdata=MultiDict({'name': 'Foo'}))

This will set the value of the name 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 hello():
    if request.method == 'GET':
        form = NewForm(formdata=MultiDict({'name': 'foo'}))
    else:
        form = NewForm()
    if form.validate_on_submit():
        # do stuff
    return render_template(template, form=form)

* A MultiDict is required because in an HTML form there may be multiple inputs with the same name attribute, and a MultiDict has methods that handle lists of values as well as single values like a normal dict.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!