简体   繁体   中英

How to use WTForms' TableWidget?

I want to use WTForms to render a form in a table. It seems like the TableWidget will do the trick, but the only way I can get this to work is as follows:

from wtforms import Form, TextField, widgets

class User(Form):
    user = TextField('User')
    email = TextField('Password')

    widget = widgets.TableWidget(with_table_tag=False)

user = User()
print user.widget(user)

This seems weird (the print user.widget(user) part) According to the documentation, I ought to be able to say:

class User(Form):
    user = TextField('User', widget=widgets.TableWidget)
    email = TextField('Password', widget=widgets.TableWidget)

user = User()
for form_field in user:
    print form_field

However, this returns TypeError: __str__ returned non-string (type TableWidget)

When I replace user, email with:

user = TextField('User')
email = TextField('Password')

Then of course the WTForms rendering works as expected.

How does this work?

In the docs it says the following about TableWidget

Renders a list of fields as a set of table rows with th/td pairs.

You are associating it a with single field instead of a list of fields. If you look in the code the __call__ method of TableWidget expects an argument called field but it treats it as an iterable for purposes of generating the html string.

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