Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 955
Zion Avatar asked Oct 12 '25 08:10

Zion


2 Answers

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"})
like image 147
davidism Avatar answered Oct 14 '25 20:10

davidism


You can use 'render_kw' in order to use placeholder in your form class.

class SignUpForm(Form):
        username = TextField("Username: ", render_kw={"placeholder": "username"}, validators=[Required(),Length(3,24)])
like image 20
Andrew Clark Avatar answered Oct 14 '25 22:10

Andrew Clark