Martin Thoma
Martin Thoma

Reputation: 136635

How can I set the class of a checkbox label with wtforms?

I would like to use Bootstrap 4 forms. This means I need to add the class form-check-label to the label of a checkbox. How can I do that?

Minimal Code Sample

requirements.txt

Flask==1.0.2
WTForms==2.2.1
Flask-WTF==0.14.2

app.py:

from flask import Flask, render_template
from flask_wtf import FlaskForm
from wtforms import BooleanField, StringField, PasswordField, SubmitField

app = Flask(__name__, template_folder="templates")
app.config['SECRET_KEY'] = 'http://flask.pocoo.org/docs/1.0/quickstart/#sessions'


class LoginForm(FlaskForm):
    username = StringField('Username')
    password = PasswordField('Password')
    remember_me = BooleanField("Remember Me")
    submit = SubmitField('Submit')


@app.route('/')
def index():
    form = LoginForm()
    return render_template('login.html', form=form)

app.run()

templates/login.html:

<form action="" method="post" class="form form-horizontal" role="form">
    {{ form.hidden_tag() }}
    <div class="form-group">
        {{ form.username.label }}<br>
        {{ form.username(size=32, class_="form-control") }}<br>
        {% for error in form.username.errors %}
        <span style="color: red;">[{{ error }}]</span>
        {% endfor %}
    </div>
    <div class="form-group">
        {{ form.password.label }}<br>
        {{ form.password(size=32, class_="form-control") }}<br>
        {% for error in form.password.errors %}
        <span style="color: red;">[{{ error }}]</span>
        {% endfor %}
    </div>
    <div class="form-check">
        {{ form.remember_me.label }}<br>  # form-check-label
       {{ form.remember_me(value='n', class_="form-check-input") }}
        {% for error in form.remember_me.errors %}
        <span style="color: red;">[{{ error }}]</span>
        {% endfor %}
    </div>
    {{ form.submit(class_="btn btn-primary") }}
</form>

Upvotes: 1

Views: 1774

Answers (1)

Martin Thoma
Martin Thoma

Reputation: 136635

The solution turned out to be super simple - I can call .label also as a function identical to the other elements:

{{ form.remember_me.label(class_="form-check-label") }}

Upvotes: 2

Related Questions