SkyTemple
SkyTemple

Reputation: 121

flaskform pass a variable (WTForms)

I want to pass a str to be used as the prompt for a form. I thought it would be simple but it is proving to be difficult.

Here is my code:

class PostForm(FlaskForm):
    post = TextAreaField(Question, validators=[DataRequired()])
    submit = SubmitField('Submit')`

And,

form = PostForm('my question')

the corresponding html

{{ wtf.quick_form(form) }}

Upvotes: 0

Views: 1347

Answers (3)

pepegc
pepegc

Reputation: 123

Try this:

def PostForm(question)
    class F(Flaskform):
        post = TextAreaField(question, validators=[DataRequired()])
        submit = SubmitField('Submit')
    return F()

Upvotes: 0

Kyrylo Kundik
Kyrylo Kundik

Reputation: 64

Today I'm figured out about a similar problem as yours. I wanted to pass a variable to FlaskForm. For a small CV creation app, I want to give the user an opportunity to create more than 1 entry for his work experience and I wanted to do it with FieldList and FormField. And I needed to do it on one page so in one form.

My solution is pretty simple python implementation of factory pattern for forms:

class ConstructorForm(FlaskForm):
    ...
    work_experience_form = FieldList(FormField(WorkExperienceForm), min_entries=1, max_entries=1)
    skills_form = FieldList(FormField(SkillsForm), min_entries=1, max_entries=1)
    ...

And here is my function for building extending forms:

def constructor_form(work_experience_forms=1, skills_forms=1):
    class _ConstructorForm(ConstructorForm):
        pass

    _ConstructorForm.work_experience_form = FieldList(
        FormField(WorkExperienceForm), min_entries=work_experience_forms, max_entries=work_experience_forms
    )
    _ConstructorForm.skills_form = FieldList(
        FormField(SkillsForm), min_entries=skills_forms, max_entries=skills_forms
    )

    return _ConstructorForm()

Upvotes: 1

SkyTemple
SkyTemple

Reputation: 121

So, I still don't have an answer to the question, but I did manage to come up with a solution.

class PostForm(FlaskForm):
    post = TextAreaField(_l('This no longer matters'), validators=[DataRequired()])
    submit = SubmitField(_l('Submit'))

And then in the routes

from wtforms.fields.core import Label
form = PostForm()
form.post.label = Label("post", 'Real question goes here')}

The explanation for this is that TextAreaField creates a label attribute on post that is accessible and changable, but it needs to be formated correctly as a Label object from wtforms.fields.core. (Simply reassigning it as a string did not work). The representation of this object is:

<label for="post">Real question goes here</label>

And it is of type

<class 'wtforms.fields.core.Label'>

Upvotes: 1

Related Questions