简体   繁体   English

不同的Form对象如何在Flask-wtforms中通信?

[英]How do different Form objects communicate in Flask-wtforms?

A typical view is something like 典型的观点是这样的

@app.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        # do stufff
        return redirect(url_for('somewhere_else', param=param))
    return render_template('login.html', form=form)

What I'm confused about: when the login() view is called, isn't a new LoginForm() instantiated with form = LoginForm() ? 我感到困惑:当login()的观点被称为,是不是一个新的LoginForm()与实例form = LoginForm() How does this brand new form ever validate_on_submit() ? 这个全新的表格如何过validate_on_submit()

It's addressed in the first page of the quick-start guide in the documentation : 在文档快速入门指南的第一页中对此进行了介绍

Note that you don't have to pass request.form to Flask-WTF; 注意,您不必将request.form传递给Flask-WTF; it will load automatically. 它会自动加载。 And the convenience validate_on_submit will check if it is a POST request and if it is valid. 并且便利的validate_on_submit将检查它是否是POST请求以及它是否有效。

So when you instantiate the form, it'll automatically load in the existing request if it can. 因此,当您实例化表单时,它将尽可能自动加载到现有请求中。

Look at the source code of flask-wtf (I removed unrelated fragments and added comments): 查看flask-wtf 的源代码 (我删除了不相关的片段并添加了注释):

class Form(SecureForm):

    # ...

    def __init__(self, formdata=_Auto, obj=None, prefix='', csrf_context=None,
                 secret_key=None, csrf_enabled=None, *args, **kwargs):

        # ...

        if formdata is _Auto:
            if self.is_submitted():
                formdata = request.form  # !!! LOOK HERE !!!
                if request.files:
                    formdata = formdata.copy()
                    formdata.update(request.files)
                elif request.json:
                    formdata = werkzeug.datastructures.MultiDict(request.json)
            else:
                formdata = None

        # ...

So, if you don't pass formdata explicitly to form's constructor and current request "is submitted" (the method is either PUT or POST), it uses the request.form . 因此,如果您没有将formdata显式传递给form的构造函数,并且当前请求“已提交”(方法是PUT或POST),则它将使用request.form

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM