ruipacheco ruipacheco - 10 months ago 118
Python Question

How can I create a form instance outside of a view?

I'm currently writing a Flask app. One of my views has very complex business logic so I moved that to a class declared outside the view. In the constructor of that class I create several instances of


My problem is that at runtime I get the following error:

*** 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.

is mine)

I assume the form objects need to be in the view? But I want to move the work of creating them into a separate class so the view won't get too complex, otherwise it's unmanageable.


You can't. flask_wtf.Form requires the application context to set up CSRF.

It doesn't really make sense to instantiate a form outside of where it will be used, because you need to instantiate it with the data that is submitted to do anything useful.

Move creating the form instances to a method that you call on that class, rather than in it's __init__ method.