Ahmad
Ahmad

Reputation: 9668

How can I remove fields from WTF form by name

I am trying to remove some fields from a wtf form:

form = super().edit_form(obj=obj)
for f in form:
    if f.name not in self.form_details_columns:
        del f
return form

This method doesn't work, however if I use something like

   del form.questin

Where question is the name of a field, it works

Upvotes: 3

Views: 175

Answers (2)

MM21
MM21

Reputation: 21

you can remove some of the WTF fields by using the del statement. the example I made is...

from flask_wtf import FlaskForm
from wtforms import StringField, IntegerField

class MyForm(FlaskForm):
    name = StringField('Name')
    age = IntegerField('Age')

# Remove the "age" field from the form
form = MyForm()
del form.age

you are able to use 'pop' to remove fields too. Example:

form._fields.pop('age')

Upvotes: 2

Ahmad
Ahmad

Reputation: 9668

Based on other answers, I solved it using:

form = super().edit_form(obj=obj)
form_columns = [f.name for f in form]
for name in form_columns:
    if name not in self.form_details_columns:
        form._fields.pop(name, None)
return form

Upvotes: 0

Related Questions