Search code examples
pythonflaskflask-wtforms

flask-wtform placeholder behavior


Form:

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

why does this work?

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

but not when you directly use placeholder as an argument for the SignUpForm?

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

it gives out this error TypeError: __init__() got an unexpected keyword argument 'placeholder'

Im a bit puzzled by this because defining it directly on the class should just be the same as doing form.username(placeholder="username") but why does it give out an error?


Solution

  • Calling a field to render it accepts arbitrary keyword args to add attributes to the input. If you want a shortcut to render a field with the label as the placeholder, you can write a Jinja macro.

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

    You can also provide args to pass to each render call when defining the field by setting the render_kw argument.

    username = TextField(render_kw={"placeholder": "username"})