如何用WTForms渲染我的TextArea?

问题描述 投票:20回答:4

要使用WTForms使用指定数量的列和行渲染我的textareafield,如何设置列数和行数?我按照这个问题的说明,但它不起作用:

How to specify rows and columns of a <textarea > tag using wtforms

我尝试添加一个小部件,但它不起作用:

class AForm(Form):
    name = TextField('Name', [validators.Length(min=4)])
    title = TextField('Title', [validators.Length(min=4)])
    text = TextAreaField('Text', widget=TextArea(row=70, cols=11))
    phonenumber = TextField('Phone number')
    phonenumberhide = BooleanField('Display phone number on site')
    price = TextField('Price')
    password = PasswordField('Password')
    email = TextField('Email', [
        validators.Length(min=6, message=_('Little short for an email address?')),
        validators.Email(message=_('That\'s not a valid email address.'))
    ])

TypeError:object.new()不带参数

python wtforms
4个回答
41
投票

很老的问题,但由于WTF-Form文档不清楚,我发布了我的工作示例。 OP,希望你还没有继续这个。 :-)

形成

from flask_wtf import Form
from wtforms.fields import StringField
from wtforms.widgets import TextArea

class PostForm(Form):
    title = StringField(u'title', validators=[DataRequired()])
    body = StringField(u'Text', widget=TextArea())

模板

{% extends "base.html" %}
{% block title %}Create Post{% endblock %}
{% block content %}
<H3>Create/Edit Post</H3>
<form action="" method=post>
   {{form.hidden_tag()}}
   <dl>
      <dt>Title:
      <dd>{{ form.title }}
      <dt>Post:
      <dd>{{ form.body(cols="35", rows="20") }}}
   </dl>
   <p>
      <input type=submit value="Publish">
</form>
{% endblock %}

25
投票

无需为此问题更新模板。您可以在TextAreaField的定义中设置行和列。这是样本:

class AForm(Form):
     text = TextAreaField('Text', render_kw={"rows": 70, "cols": 11})

对于render_kw,如果提供,将在渲染时向窗口小部件提供提供默认关键字的字典。


20
投票

TextArea字段也可以在没有任何小部件的情况下实现:

forms.朋友

from wtforms import Form, TextField, TextAreaField

class ContactForm(Form):
    name = TextField('Name')
    email = TextField('Email Address')
    body = TextAreaField('Message Body')

template.html

... 
    <form method="POST" action="">
        {{ form.csrf_token }}
        {{ form.name.label }} {{ form.name(size=30) }} <br/>
        {{ form.email.label }} {{ form.email(size=30) }} <br/>
        {{ form.body.label }} {{ form.body(cols="35", rows="20") }} <br/>
        <input type="submit" value="Submit"/>
    </form>
...

0
投票

我想在此添加上面建议使用render_kw的解决方案确实在条件下工作,即文本区域的高度未设置。

所以,如果你有一个字段:

    temp = TextAreaField('temp', render_kw={'rows':20})

并在您的HTML文件中写道:

    {{ form.temp(class_='someclass' )}}

然后在someclass的CSS定义中,不应该设置height,因为这会与你的行设置冲突,显然height的优先级高于行。

© www.soinside.com 2019 - 2024. All rights reserved.