Skip to content Skip to sidebar Skip to footer

Wtforms-how To Prepopulate A Textarea Field?

Hi I have been trying to pepopulate a textareafield using something like this in the template. {{form.content(value='please type content')}} This works when the field is textfield

Solution 1:

You can do it before rendering, something like:

form.content.data = 'please type content'

I'm new to WTForms though.

Solution 2:

For textarea widgets, you set the default content with the default argument in your field constructors.

classYourForm(Form):
    your_text_area =TextAreaField("TextArea", default="please add content")

Then when you render:

{{form.content()}}

WTForms will render the default text. I have not been able to find a way to specify default text for the text area at render time.

Solution 3:

I recently had the same problem, I solved it like this:

{% set f = form.content.process_data("please type content") %}
{{ form.content() }}

For a test, you can try run the follow snippet:

>>> import wtforms
>>> import jinja2
>>> from wtforms.fields import TextAreaField
>>> classMyForm(wtforms.Form):
...     content = TextAreaField("Text Area")
... >>> t = jinja2.Template("""{% set f = form.content.process_data("please type content") %}
...                     {{ form.content() }}""")
>>> >>> t.render(form=MyForm())
u'\n                    <textarea id="content" name="content">please type content</textarea>'

Solution 4:

Alice there seems to be support built into the form widget to do what you are after but you are right it doesn't work at the moment.

Sean and hilquias post decent work arounds which do work. This is the form (yuk yuk) you might try

else:
        form.title.data=blog.title
        form.blogdata.data=blog.blogdata
    return render_template('editblog.html',form=form)

Solution 5:

For those trying to do this dynamically in jinja template, setting the default value prior to rendering does not fix this problem.

Instead of using the WTForms standard:

{{ form.content() }}

You can construct this element with raw HTML like:

<textarea id="FormName-content" name="FormName-content">{{ dynamic values here }}</textarea>

...and it will still work with your WTForms validation.

Hope this helps someone :)

Post a Comment for "Wtforms-how To Prepopulate A Textarea Field?"