WTForms-如何预填充textarea字段?

Ras*_*mus 18 python flask wtforms

嗨,我一直试图在模板中使用类似的东西来填充textareafield.

{{form.content(value="please type content")}}
Run Code Online (Sandbox Code Playgroud)

当字段是文本字段时,这主要是因为html接受值,<input type="text"> 但同样不适用于textarea ...有人可以帮我这个吗?

小智 31

您可以在渲染之前执行此操作,例如:

form.content.data = 'please type content'
Run Code Online (Sandbox Code Playgroud)

我是WTForms的新手.

  • 当我这样做时,不会记录提交的任何数据。 (3认同)

Sea*_*ira 16

对于textarea窗口小部件,可以使用default字段构造函数中的参数设置默认内容.

class YourForm(Form):
    your_text_area = TextAreaField("TextArea", default="please add content")
Run Code Online (Sandbox Code Playgroud)

然后当你渲染:

{{form.content()}}
Run Code Online (Sandbox Code Playgroud)

WTForms将呈现默认文本.我无法在渲染时找到为文本区域指定默认文本的方法.

  • 谢谢肖恩!但我需要在模板中做到这一点.它类似于编辑博客链接.当您针对任何博客单击编辑按钮时,它应该在文本字段中显示带有标题的表单(使用value参数完成)和textarea字段中的博客内容. (2认同)

Jor*_*rín 13

我最近遇到了同样的问题,我解决了这个问题:

{% set f = form.content.process_data("please type content") %}
{{ form.content() }}
Run Code Online (Sandbox Code Playgroud)

对于测试,您可以尝试运行以下代码段:

>>> import wtforms
>>> import jinja2
>>> from wtforms.fields import TextAreaField
>>> class MyForm(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>'
Run Code Online (Sandbox Code Playgroud)


小智 6

爱丽丝似乎已经在窗体小部件中内置了支持来完成你所追求的但是你是对的它现在不起作用.

Sean和hilquias发布了可行的体面工作.这是你可能尝试的形式(yuk yuk)

 else:
        form.title.data=blog.title
        form.blogdata.data=blog.blogdata
    return render_template('editblog.html',form=form)
Run Code Online (Sandbox Code Playgroud)


bro*_*oox 5

TextArea使用字段定义您的表单

class MyForm(Form):
    name = fields.StringField('Name', validators=[Required()])
    description = fields.TextAreaField('Description')
Run Code Online (Sandbox Code Playgroud)

在渲染模板之前设置文本区域内容

form = MyForm()
form.description.data='this is my textarea content!' # This is the stuff...
return render_template('form.html', form=form, name=name)
Run Code Online (Sandbox Code Playgroud)

渲染模板中的字段

<form ...>
    {{ field(form.name, value=name) }}
    {{ field(form.description, rows=2) }}
    <button ...>Save</button>
</form>
Run Code Online (Sandbox Code Playgroud)


G. *_*and 5

对于那些试图jinja 模板中动态执行此操作的人,在渲染之前设置默认值并不能解决此问题。

而不是使用 WTForms 标准:

{{ form.content() }}
Run Code Online (Sandbox Code Playgroud)

您可以使用原始 HTML 构建此元素,例如:

<textarea id="FormName-content" name="FormName-content">{{ dynamic values here }}</textarea>
Run Code Online (Sandbox Code Playgroud)

...它仍然适用于您的 WTForms 验证。

希望这对某人有所帮助:)