WTForms 当我启动一个字段时,我可以添加一个占位符属性吗?

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

我想在WTForms中给字段添加一个占位符属性。我怎么做呢?

abc = TextField('abc', validators=[Required(), Length(min=3, max=30)], placeholder="test")

上面的代码是无效的

如何添加带值的占位符属性?

python wtforms
4个回答
130
投票

WTForms 2.1更新

从 WTForms 2.1(2015 年 12 月)开始,您可以通过以下方式设置渲染关键字。render_kw= 参数给字段构造函数。

所以这个字段看起来会是这样的。

abc = StringField('abc', [InputRequired()], render_kw={"placeholder": "test"})

请注意,虽然这是有可能的,但它确实开始在代码和表现之间架起了一座桥梁,所以要明智地使用它。


(老答案,对于 WTForms 2.1 以上的版本仍然适用)

placeholder 在 WTforms 2.0.x 及以下版本的 Python 构造函数中不支持。

但是,您可以在您的模板中轻松地做到这一点。

{{ form.abc(placeholder="test") }}

7
投票

正确答案如下。

abc = TextField('abc', validators=[Required(), Length(min=3, max=30)], description="test")

您可以在文档中读到。

description – A description for the field, typically used for help text.

然后在您的模板中。

{% import 'forms.html' as forms %}

{% for field in form %}
    {{ forms.render_field(field) }}
{% endfor %}

其中 render_field 是一个定义在 forms.html 中的宏。

{% macro render_field(field) -%}

{% if field.type == 'CSRFTokenField' %}
    {{ field }}

    {% if field.errors %}
        <div class="warning">You have submitted an invalid CSRF token</div>
    {% endif %}
{% elif field.type == 'HiddenField' %}
    {{ field }}
{# any other special case you may need #}
{% else %}
    <div class="form-group">
        <label for="{{ field.label.field_id }}" class="col-sm-2 control-label">{{ field.label.text }}</label>
        <div class="col-sm-10">
            {{ field(placeholder=field.description) }}
            {% if field.errors %}
                <div class="alert alert-danger" role="alert">
                {% for err in field.errors %}
                    <p>{{ err|e }}</p>
                {% endfor %}
                </div>
            {% endif %}
        </div>
    </div>
{% endif %}

{%- endmacro %}

2
投票

我的解决方案是使用一个自定义的widget。

from flask.ext.wtf import Form
from wtforms import StringField, validators
from wtforms.widgets import Input


class CustomInput(Input):
    input_type = None

    def __init__(self, input_type=None, **kwargs):
        self.params = kwargs
        super(CustomInput, self).__init__(input_type=input_type)

    def __call__(self, field, **kwargs):
        for param, value in self.params.iteritems():
            kwargs.setdefault(param, value)
        return super(CustomInput, self).__call__(field, **kwargs)


class CustomTextInput(CustomInput):
    input_type = 'text'


class EditProfileForm(Form):
    first_name = StringField('First name',
                             validators=[validators.DataRequired()],
                             widget=CustomTextInput(placeholder='Enter first name'))

也许这并不完美, 但它允许使用Flask -Bootstrap 并在表单代码中定义你的表单, 而不是在模板中.


0
投票
{{ form.username(class="input", placeholder="Please enter your username") }} 
© www.soinside.com 2019 - 2024. All rights reserved.