如何在视图外创建表单实例?

时间:2016-06-29 16:53:02

标签: python flask wtforms flask-wtforms

我正在撰写Flask应用。我的一个视图具有非常复杂的业务逻辑,因此我将其移动到视图外部声明的类。在该类的构造函数中,我创建了几个flask_wtf.form.Form个对象的实例。

我的问题是在运行时我收到以下错误:

*** RuntimeError: Working outside of application context.

This typically means that you attempted to use functionality that needed
to interface with the current application object in a way.  To solve
this set up an application context with app.app_context().  See the
documentation for more information.

ipdb是我的)

我假设表单对象需要在视图中?但我想将创建它们的工作转移到一个单独的类中,这样视图就不会太复杂,否则就无法管理。

1 个答案:

答案 0 :(得分:2)

你不能。 flask_wtf.Form需要应用程序上下文来设置CSRF。

在表单之外实例化表单并不合理,因为您需要使用提交的数据对其进行实例化以执行任何有用的操作。

将表单实例创建移动到您在该类上调用的方法,而不是在其__init__方法中。