Change value of a textarea using flask-wtforms

Viewed 3014

I am using flask-wtforms to create a Textarea.

body = TextAreaField('body')

I want to change the value of the textarea which you can do in html like this.

<textarea>other value then default</textarea>

How can I integrate this with flask-wtforms?

My template looks like this:

{{ form.body(rows="20") }} <!--texarea -->

With a simple input field I could do something like this:

{{ form.body(value="other value then default") }} <!-- input field -->

I need to set the default value in the template itself. Because it will have info over the article the page is about.

4 Answers

Weird that 2 years after this question was asked, there's still no standard way to implement this.

What I do is write it out in plain HTML:

<textarea id="body" name="body">{{ value }}</textarea>

This works fine and the textarea is validated normally

You can create a widget that defines an entire alternative html behavior, like so:

in widgets.py

from markupsafe import Markup
from wtforms.widgets import html_params


class BodyWidget(object):
    data_template = (
        '<textarea %(text)s >other value then default</textarea>'
    )

    def __call__(self, field, **kwargs):
        kwargs.setdefault("id", field.id)
        kwargs.setdefault("name", field.name)
        template = self.data_template
        return Markup(
            template % {"text": html_params(type="text", value=(field.data or ""), rows=20, cols=50, **kwargs)}
        )

in forms.py

from widgets import BodyWidget

body = TextAreaField('body', widget=BodyWidget())
Related