Category Archives: python

WTforms: how to set autofocus, required

wtforms version: 2.1

First of all, in my opinion autofocus, required should be set in template side, not in webforms class you define. ( well, it depends )

Let’s say there is LoginForm classlike this.

from wtforms import validators, Form, StringField, PasswordField, HiddenField, BooleanField
from wtforms.fields.html5 import EmailField

STRIP_FILTER = lambda x: x.strip() if x else None

class LoginForm(Form):
    """
    Form for login
    """
    email = EmailField(
        label=u'Login Email',
        id="input_email",
        validators=[validators.Length(min=1, max=30), validators.required()],
        filters=[STRIP_FILTER])
    password = PasswordField(
        label=u'Login Password',
        id="input_password",
        validators=[validators.Length(min=1, max=30), validators.required()],
        filters=[STRIP_FILTER])
    remember_me = BooleanField(label=u'Remember me')

placeholder, autofocus, required attributes can be set like this

{{ form.email.label(class="sr-only") }}
{{ form.email(class_='form-control', placeholder="Email address", autofocus=True, required=True, value="abc@be.com") }}
{{ form.password.label(class="sr-only") }}
{{ form.password(class_='form-control', placeholder="Password", required=True, value="12345") }}

Some jinja version uses lower case ‘true’ rather than ‘True’. Therefore, if ‘True’ doesn’t work for you, then try again with ‘true’.

If autofocus and required need to be set in LoginForm, render_kw kwags can be used.

class LoginForm(Form):
    """
    Form for login
    """
    email = EmailField(
        label=u'Login Email',
        id="input_email",
        render_kw={'required': True,
                   'placeholder': "Email address"},
        validators=[validators.Length(min=1, max=30), validators.required()],
        filters=[STRIP_FILTER])
    password = PasswordField(
        label=u'Login Password',
        id="input_password",
        render_kw={'required': True,
                   'placeholder': "Password"},
        validators=[validators.Length(min=1, max=30), validators.required()],
        filters=[STRIP_FILTER])
    remember_me = BooleanField(label=u'Remember me')