简体   繁体   中英

How can I use a Form subclass as a data attribute of another Form subclass?

I want to do something like this, but don't know if it is possible in any way:

    from flask.ext.wtf import Form, TextField
    class Foo(Form):
        a = TextField('name')
    class Bar(Form):
        b = Foo()

The error I'm getting is

   Traceback (most recent call last):
   File "data_attr.py", line 4, in <module>
     class Bar(Form):
   File "data_attr.py", line 5, in Bar
     b = Foo()
   File "/usr/local/lib/python2.7/dist-packages/wtforms/form.py", line 178, in __call__
     return type.__call__(cls, *args, **kwargs)
   File "/usr/local/lib/python2.7/dist-packages/flask_wtf/form.py", line 44, in __init__
     csrf_enabled = current_app.config.get('CSRF_ENABLED', True)
   File "/usr/local/lib/python2.7/dist-packages/werkzeug/local.py", line 336, in __getattr__
     return getattr(self._get_current_object(), name)
   File "/usr/local/lib/python2.7/dist-packages/werkzeug/local.py", line 295, in _get_current_object
     return self.__local()
   File "/usr/local/lib/python2.7/dist-packages/flask/globals.py", line 26, in _find_app
     raise RuntimeError('working outside of application context')
   RuntimeError: working outside of application context

Is there any other way to do it? Thanks!

You can use a Field Enclosure via the FormField class

class Foo(Form):
    a = TextField('name')

class Bar(Form):
    b = FormField(Foo)

http://wtforms.simplecodes.com/docs/1.0.3/fields.html#field-enclosures

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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