WTForms Can I add a placeholder attribute when I init a field?

PythonWtforms

Python Problem Overview


I want to add a placeholder attribute on to the field in WTForms. How can I do it?

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

The above code is not valid

How can I add a placeholder attribute with value?

Python Solutions


Solution 1 - Python

Updated for WTForms 2.1

You can now as of WTForms 2.1 (December 2015) set rendering keywords by using the render_kw= parameter to the field constructor.

So the field would look like:

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

Note while this is possible; it does start to bridge the line between code and presentation; so use it wisely!


(Old answer, still true for versions older than WTForms 2.1)

placeholder is not supported in the Python constructor in WTforms 2.0.x and below.

However, you can do this easily in your template:

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

Solution 2 - Python

Correct answer is as follows:

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

As one can read in documenatation:

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

Then in your template:

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

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

Where render_field is a macro that is defined in 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 %}

Solution 3 - Python

{{ form.username(class="input", placeholder="Please enter your username") }} 

Solution 4 - Python

My solution is use a custom 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'))

Maybe it's not ellegant, but it allows to use Flask-Bootstrap and define your forms in the forms code, not in the template

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTheOneTeamView Question on Stackoverflow
Solution 1 - PythonCrastView Answer on Stackoverflow
Solution 2 - PythonDrachenfelsView Answer on Stackoverflow
Solution 3 - PythonPasham Akhil Kumar ReddyView Answer on Stackoverflow
Solution 4 - PythonNikolai GolubView Answer on Stackoverflow