Search code examples
pythonflaskflask-wtformswtforms

Reuse wtforms field in multiple forms


I have a bunch of forms that have similar fields. To simplify my code, I'd like to define the fields outside of the forms and then add the fields to the forms as needed like this:

name = wt.StringField("name")
age = wt.StringField("age")

class Form1(FlaskForm):
    name=name

class Form2(FlaskForm):
    age=age

class Form3(FlaskForm):
    name=name
    age=age

This pattern seems to work, but I've never seen anyone do this before so I want to make sure that there are not edge cases where this will break. If so, are there better ways of doing this?


Solution

  • Although the pattern in my question works, I'm nervous about using it since it doesn't appear to be a recommended way of doing things. This is a safer approach that meets my needs:

    def name_field(): return wt.StringField("name")
    def age_field(): return wt.StringField("age")
    
    class Form1(FlaskForm):
        name=name_field()
    
    class Form2(FlaskForm):
        age=age_field()
    
    class Form3(FlaskForm):
        name=name_field()
        age=age_field()