0

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?

2 Answers 2

2

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()
Sign up to request clarification or add additional context in comments.

1 Comment

what if i want to add a new validator in this case. Exp in Form3 add a custum name validator
0

It seems to me FormField is what you're looking for.

class nameForm(Form):
    name = wt.StringField("name")


class ageForm(Form):
    age = wt.StringField("age")


class Form1(FlaskForm):
    name = FormField(nameForm)


class Form2(FlaskForm):
    age = FormField(ageForm)


class Form3(FlaskForm):
    name = FormField(nameForm)
    age = FormField(ageForm)

Here's some relevant documentation -> https://wtforms.readthedocs.io/en/2.3.x/fields/

Search this doc for the Field Enclosures Section

3 Comments

You could also do it without FormField like this class Form1(nameForm): pass. That is what I was doing before but I like the solution in my answer better.
@gaefan that's a neat way of doing it. I've done similar things for validating or populating forms but I did not realize you could call functions returning the actual Form Field. Cool solution!
Best documentation for FlaskForm. One parameter is missing though: choices. Maybe more

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.