flask-wtform 占位符行为

flask-wtform placeholder behavior

表格:

class SignUpForm(Form):
    username = TextField("Username: ",validators=[Required(),Length(3,24)])

为什么这样做?

form = SignUpForm()
form.username(placeholder="username")

但当您直接使用占位符作为 SignUpForm?

的参数时则不然
class SignUpForm(Form):
        username = TextField("Username: ",placeholder="username",validators=[Required(),Length(3,24)])

它给出了这个错误 TypeError: __init__() got an unexpected keyword argument 'placeholder'

我对此有点困惑,因为直接在 class 上定义它应该与 做 form.username(placeholder="username") 但为什么它给出错误?

定义字段不同于呈现字段。 Calling a field to render it accepts arbitrary keyword args to add attributes to the input. 库在定义字段时并未设计为采用任意参数。

如果你想要一个快捷方式来渲染一个以标签作为占位符的字段,你可以写一个 Jinja 宏。

{% macro form_field(field) %}
{{ field(placeholder=field.label.text) }}
{% endmacro %}

您可以使用 'render_kw' 以便在表单中使用占位符 class。

class SignUpForm(Form):
        username = TextField("Username: ", render_kw={"placeholder": "username"}, validators=[Required(),Length(3,24)])