Fields are responsible for rendering and data conversion. They delegate to validators for data validation.

Field definitions

Fields are defined as members on a form in a declarative fashion:

class MyForm(Form):
    name    = StringField(u'Full Name', [validators.required(), validators.length(max=10)])
    address = TextAreaField(u'Mailing Address', [validators.optional(), validators.length(max=200)])

When a field is defined on a form, the construction parameters are saved until the form is instantiated. At form instantiation time, a copy of the field is made with all the parameters specified in the definition. Each instance of the field keeps its own field data and errors list.

The label and validators can be passed to the constructor as sequential arguments, while all other arguments should be passed as keyword arguments. Some fields (such as SelectField) can also take additional field-specific keyword arguments. Consult the built-in fields reference for information on those.

The Field base class

class wtforms.fields.Field

Stores and processes data, and generates HTML for a form field.

Field instances contain the data of that instance as well as the functionality to render it within your Form. They also contain a number of properties which can be used within your templates to render the field and label.


__init__(label=None, validators=None, filters=(), description=u'', id=None, default=None, widget=None, render_kw=None, _form=None, _name=None, _prefix=u'', _translations=None, _meta=None)

Construct a new field.

  • label – The label of the field.
  • validators – A sequence of validators to call when validate is called.
  • filters – A sequence of filters which are run on input data by process.
  • description – A description for the field, typically used for help text.
  • id – An id to use for the field. A reasonable default is set by the form, and you shouldn’t need to set this manually.
  • default – The default value to assign to the field, if no form or object input is provided. May be a callable.
  • widget – If provided, overrides the widget used to render the field.
  • render_kw (dict) – If provided, a dictionary which provides default keywords that will be given to the widget at render time.
  • _form – The form holding this field. It is passed by the form itself during construction. You should never pass this value yourself.
  • _name – The name of this field, passed by the enclosing form during its construction. You should never pass this value yourself.
  • _prefix – The prefix to prepend to the form name of this field, passed by the enclosing form during construction.
  • _translations – A translations object providing message translations. Usually passed by the enclosing form during construction. See I18n docs for information on message translations.
  • _meta – If provided, this is the ‘meta’ instance from the form. You usually don’t pass this yourself.

If _form and _name isn’t provided, an UnboundField will be returned instead. Call its bind() method with a form instance and a name to construct the field.


To validate the field, call its validate method, providing a form and any extra validators needed. To extend validation behaviour, override pre_validate or post_validate.

validate(form, extra_validators=())

Validates the field and returns True or False. self.errors will contain any errors raised during validation. This is usually only called by Form.validate.

Subfields shouldn’t override this, but rather override either pre_validate, post_validate or both, depending on needs.

  • form – The form the field belongs to.
  • extra_validators – A sequence of extra validators to run.

Override if you need field-level validation. Runs before any other validators.

Parameters:form – The form the field belongs to.
post_validate(form, validation_stopped)

Override if you need to run any field-level validation tasks after normal validation. This shouldn’t be needed in most cases.

  • form – The form the field belongs to.
  • validation_stoppedTrue if any validator raised StopValidation.

If validate encounters any errors, they will be inserted into this list.

Data access and processing

To handle incoming data from python, override process_data. Similarly, to handle incoming data from the outside, override process_formdata.

process(formdata[, data])

Process incoming data, calling process_data, process_formdata as needed, and run filters.

If data is not provided, process_data will be called on the field’s default.

Field subclasses usually won’t override this, instead overriding the process_formdata and process_data methods. Only override this for special advanced processing, such as when a field encapsulates many inputs.


Process the Python data applied to this field and store the result.

This will be called during form construction by the form’s kwargs or obj argument.

Parameters:value – The python object containing the value to process.

Process data received over the wire from a form.

This will be called during form construction with data supplied through the formdata argument.

Parameters:valuelist – A list of strings to process.

Contains the resulting (sanitized) value of calling either of the process methods. Note that it is not HTML escaped when using in templates.


If form data is processed, is the valuelist given from the formdata wrapper. Otherwise, raw_data will be None.


This is the data passed from an object or from kwargs to the field, stored unmodified. This can be used by templates, widgets, validators as needed (for comparison, for example)


To render a field, simply call it, providing any values the widget expects as keyword arguments. Usually the keyword arguments are used for extra HTML attributes.


Render this field as HTML, using keyword args as additional attributes.

This delegates rendering to meta.render_field whose default behavior is to call the field’s widget, passing any keyword arguments from this call along to the widget.

In all of the WTForms HTML widgets, keyword arguments are turned to HTML attributes, though in theory a widget is free to do anything it wants with the supplied keyword arguments, and widgets don’t have to even do anything related to HTML.

If one wants to pass the “class” argument which is a reserved keyword in some python-based templating languages, one can do:


This will output (for a text field):

<input type="text" name="field_name" value="blah" class="text_blob" id="field_name" />

Note: Simply coercing the field to a string or unicode will render it as if it was called with no arguments.


Returns a HTML representation of the field. For more powerful rendering, see the __call__() method.

Many template engines use the __html__ method when it exists on a printed object to get an ‘html-safe’ string that will not be auto-escaped. To allow for printing a bare field without calling it, all WTForms fields implement this method as well.

Message Translations


Get a translation for the given message.

This proxies for the internal translations object.

Parameters:string – A unicode string to be translated.
Returns:A unicode string which is the translated output.
ngettext(singular, plural, n)

Get a translation for a message which can be pluralized.

  • singular (str) – The singular form of the message.
  • plural (str) – The plural form of the message.
  • n (int) – The number of elements this message is referring to



The HTML form name of this field. This is the name as defined in your Form prefixed with the prefix passed to the Form constructor.


The un-prefixed name of this field.


The HTML ID of this field. If unspecified, this is generated for you to be the same as the field name.


This is a Label instance which when evaluated as a string returns an HTML <label for="id"> construct.


This is whatever you passed as the default to the field’s constructor, otherwise None.


A string containing the value of the description passed in the constructor to the field; this is not HTML escaped.


A sequence containing the validation errors for this field.


Errors obtained during input processing. These will be prepended to the list of errors at validation time.


The widget used to render the field.


The type of this field, as a string. This can be used in your templates to do logic based on the type of field:

{% for field in form %}
    {% if field.type == "BooleanField" %}
        <td>{{ field }} {{ field.label }}</td>
    {% else %}
        <td>{{ field.label }}</td>
        <td>{{ field }}</td>
    {% end %}
{% endfor %}

An object containing boolean flags set either by the field itself, or by validators on the field. For example, the built-in InputRequired validator sets the required flag. An unset flag will result in False.

{% for field in form %}
        <th>{{ field.label }} {% if field.flags.required %}*{% endif %}</th>
        <td>{{ field }}</td>
{% endfor %}

The same meta object instance as is available as Form.meta


The same sequence of filters that was passed as the filters= to the field constructor. This is usually a sequence of callables.

Basic fields

Basic fields generally represent scalar data types with single values, and refer to a single input from the form.

class wtforms.fields.BooleanField(default field arguments, false_values=None)

Represents an <input type="checkbox">. Set the checked-status by using the default-option. Any value for default, e.g. default="checked" puts checked into the html-element and sets the data to True

Parameters:false_values – If provided, a sequence of strings each of which is an exact match string of what is considered a “false” value. Defaults to the tuple ('false', '')
class wtforms.fields.DateField(default field arguments, format='%Y-%m-%d')

Same as DateTimeField, except stores a

class wtforms.fields.DateTimeField(default field arguments, format='%Y-%m-%d %H:%M:%S')

A text field which stores a datetime.datetime matching a format.

For better date/time fields, see the dateutil extension

class wtforms.fields.DecimalField(default field arguments, places=2, rounding=None, use_locale=False, number_format=None)

A text field which displays and coerces data of the decimal.Decimal type.

  • places – How many decimal places to quantize the value to for display on form. If None, does not quantize value.
  • rounding – How to round the value during quantize, for example decimal.ROUND_UP. If unset, uses the rounding value from the current thread’s context.
  • use_locale – If True, use locale-based number formatting. Locale-based number formatting requires the ‘babel’ package.
  • number_format – Optional number format for locale. If omitted, use the default decimal format for the locale.
class wtforms.fields.FileField(default field arguments)

Renders a file upload field.

By default, the value will be the filename sent in the form data. WTForms does not deal with frameworks’ file handling capabilities. A WTForms extension for a framework may replace the filename value with an object representing the uploaded data.

Example usage:

class UploadForm(Form):
    image        = FileField(u'Image File', [validators.regexp(u'^[^/\\]\.jpg$')])
    description  = TextAreaField(u'Image Description')

    def validate_image(form, field):
   = re.sub(r'[^a-z0-9_.-]', '_',

def upload(request):
    form = UploadForm(request.POST)
        image_data = request.FILES[].read()
        open(os.path.join(UPLOAD_PATH,, 'w').write(image_data)
class wtforms.fields.MultipleFileField(default field arguments)

A FileField that allows choosing multiple files.

class wtforms.fields.FloatField(default field arguments)

A text field, except all input is coerced to an float. Erroneous input is ignored and will not be accepted as a value.

For the majority of uses, DecimalField is preferable to FloatField, except for in cases where an IEEE float is absolutely desired over a decimal value.

class wtforms.fields.IntegerField(default field arguments)

A text field, except all input is coerced to an integer. Erroneous input is ignored and will not be accepted as a value.

class wtforms.fields.RadioField(default field arguments, choices=[], coerce=unicode)

Like a SelectField, except displays a list of radio buttons.

Iterating the field will produce subfields (each containing a label as well) in order to allow custom rendering of the individual radio fields.

{% for subfield in %}
        <td>{{ subfield }}</td>
        <td>{{ subfield.label }}</td>
{% endfor %}

Simply outputting the field without iterating its subfields will result in a <ul> list of radio choices.

class wtforms.fields.SelectField(default field arguments, choices=[], coerce=unicode, option_widget=None)

Select fields keep a choices property which is a sequence of (value, label) pairs. The value portion can be any type in theory, but as form data is sent by the browser as strings, you will need to provide a function which can coerce the string representation back to a comparable object.

Select fields with static choice values:

class PastebinEntry(Form):
    language = SelectField(u'Programming Language', choices=[('cpp', 'C++'), ('py', 'Python'), ('text', 'Plain Text')])

Note that the choices keyword is only evaluated once, so if you want to make a dynamic drop-down list, you’ll want to assign the choices list to the field after instantiation. Any inputted choices which are not in the given choices list will cause validation on the field to fail.

Select fields with dynamic choice values:

class UserDetails(Form):
    group_id = SelectField(u'Group', coerce=int)

def edit_user(request, id):
    user = User.query.get(id)
    form = UserDetails(request.POST, obj=user)
    form.group_id.choices = [(, for g in Group.query.order_by('name')]

Note we didn’t pass a choices to the SelectField constructor, but rather created the list in the view function. Also, the coerce keyword arg to SelectField says that we use int() to coerce form data. The default coerce is unicode().

Advanced functionality

SelectField and its descendants are iterable, and iterating it will produce a list of fields each representing an option. The rendering of this can be further controlled by specifying option_widget=.

class wtforms.fields.SelectMultipleField(default field arguments, choices=[], coerce=unicode, option_widget=None)

No different from a normal select field, except this one can take (and validate) multiple choices. You’ll need to specify the HTML size attribute to the select field when rendering.

The data on the SelectMultipleField is stored as a list of objects, each of which is checked and coerced from the form input. Any inputted choices which are not in the given choices list will cause validation on the field to fail.

class wtforms.fields.SubmitField(default field arguments)

Represents an <input type="submit">. This allows checking if a given submit button has been pressed.

class wtforms.fields.StringField(default field arguments)

This field is the base for most of the more complicated fields, and represents an <input type="text">.

{{ form.username(size=30, maxlength=50) }}

Convenience Fields

class wtforms.fields.HiddenField(default field arguments)

HiddenField is a convenience for a StringField with a HiddenInput widget.

It will render as an <input type="hidden"> but otherwise coerce to a string.

HiddenField is useful for providing data from a model or the application to be used on the form handler side for making choices or finding records. Very frequently, CRUD forms will use the hidden field for an object’s id.

Hidden fields are like any other field in that they can take validators and values and be accessed on the form object. You should consider validating your hidden fields just as you’d validate an input field, to prevent from malicious people playing with your data.

class wtforms.fields.PasswordField(default field arguments)

A StringField, except renders an <input type="password">.

Also, whatever value is accepted by this field is not rendered back to the browser like normal fields.

class wtforms.fields.TextAreaField(default field arguments)

This field represents an HTML <textarea> and can be used to take multi-line input.

Field Enclosures

Field enclosures allow you to have fields which represent a collection of fields, so that a form can be composed of multiple re-usable components or more complex data structures such as lists and nested objects can be represented.

class wtforms.fields.FormField(form_class, default field arguments, separator='-')

Encapsulate a form as a field in another form.

  • form_class – A subclass of Form that will be encapsulated.
  • separator – A string which will be suffixed to this field’s name to create the prefix to enclosed fields. The default is fine for most uses.

FormFields are useful for editing child objects or enclosing multiple related forms on a page which are submitted and validated together. While subclassing forms captures most desired behaviours, sometimes for reusability or purpose of combining with FieldList, FormField makes sense.

For example, take the example of a contact form which uses a similar set of three fields to represent telephone numbers:

class TelephoneForm(Form):
    country_code = IntegerField('Country Code', [validators.required()])
    area_code    = IntegerField('Area Code/Exchange', [validators.required()])
    number       = StringField('Number')

class ContactForm(Form):
    first_name   = StringField()
    last_name    = StringField()
    mobile_phone = FormField(TelephoneForm)
    office_phone = FormField(TelephoneForm)

In the example, we reused the TelephoneForm to encapsulate the common telephone entry instead of writing a custom field to handle the 3 sub-fields. The data property of the mobile_phone field will return the data dict of the enclosed form. Similarly, the errors property encapsulate the forms’ errors.

class wtforms.fields.FieldList(unbound_field, default field arguments, min_entries=0, max_entries=None)

Encapsulate an ordered list of multiple instances of the same field type, keeping data as a list.

>>> authors = FieldList(StringField('Name', [validators.DataRequired()]))
  • unbound_field – A partially-instantiated field definition, just like that would be defined on a form directly.
  • min_entries – if provided, always have at least this many entries on the field, creating blank ones if the provided input does not specify a sufficient amount.
  • max_entries – accept no more than this many entries as input, even if more exist in formdata.

Note: Due to a limitation in how HTML sends values, FieldList cannot enclose BooleanField or SubmitField instances.


Create a new entry with optional default data.

Entries added in this way will not receive formdata however, and can only receive object data.


Removes the last entry from the list and returns it.


Each entry in a FieldList is actually an instance of the field you passed in. Iterating, checking the length of, and indexing the FieldList works as expected, and proxies to the enclosed entries list.

Do not resize the entries list directly, this will result in undefined behavior. See append_entry and pop_entry for ways you can manipulate the list.


FieldList is not limited to enclosing simple fields; and can indeed represent a list of enclosed forms by combining FieldList with FormField:

class IMForm(Form):
    protocol = SelectField(choices=[('aim', 'AIM'), ('msn', 'MSN')])
    username = StringField()

class ContactForm(Form):
    first_name  = StringField()
    last_name   = StringField()
    im_accounts = FieldList(FormField(IMForm))

Custom Fields

While WTForms provides customization for existing fields using widgets and keyword argument attributes, sometimes it is necessary to design custom fields to handle special data types in your application.

Let’s design a field which represents a comma-separated list of tags:

class TagListField(Field):
    widget = TextInput()

    def _value(self):
            return u', '.join(
            return u''

    def process_formdata(self, valuelist):
        if valuelist:
   = [x.strip() for x in valuelist[0].split(',')]
   = []

The _value method is called by the TextInput widget to provide the value that is displayed in the form. Overriding the process_formdata() method processes the incoming form data back into a list of tags.

Fields With Custom Constructors

Custom fields can also override the default field constructor if needed to provide additional customization:

class BetterTagListField(TagListField):
    def __init__(self, label='', validators=None, remove_duplicates=True, **kwargs):
        super(BetterTagListField, self).__init__(label, validators, **kwargs)
        self.remove_duplicates = remove_duplicates

    def process_formdata(self, valuelist):
        super(BetterTagListField, self).process_formdata(valuelist)
        if self.remove_duplicates:
   = list(self._remove_duplicates(

    def _remove_duplicates(cls, seq):
        """Remove duplicates in a case insensitive, but case preserving manner"""
        d = {}
        for item in seq:
            if item.lower() not in d:
                d[item.lower()] = True
                yield item

When you override a Field’s constructor, to maintain consistent behavior, you should design your constructor so that:

  • You take label=’‘, validators=None as the first two positional arguments
  • Add any additional arguments your field takes as keyword arguments after the label and validators
  • Take **kwargs to catch any additional keyword arguments.
  • Call the Field constructor first, passing the first two positional arguments, and all the remaining keyword args.

Considerations for overriding process()

For the vast majority of fields, it is not necessary to override Field.process(). Most of the time, you can achieve what is needed by overriding process_data and/or process_formdata. However, for special types of fields, such as form enclosures and other special cases of handling multiple values, it may be needed.

If you are going to override process(), be careful about how you deal with the formdata parameter. For compatibility with the maximum number of frameworks, we suggest you limit yourself to manipulating formdata in the following ways only:

  • Testing emptiness: if formdata
  • Checking for key existence: key in formdata
  • Iterating all keys: for key in formdata (note that some wrappers may return multiple instances of the same key)
  • Getting the list of values for a key: formdata.getlist(key).

Most importantly, you should not use dictionary-style access to work with your formdata wrapper, because the behavior of this is highly variant on the wrapper: some return the first item, others return the last, and some may return a list.

Additional Helper Classes

class wtforms.fields.Flags

Holds a set of boolean flags as attributes.

Accessing a non-existing attribute returns False for its value.


>>> flags = Flags()
>>> flags.required = True
>>> 'required' in flags
>>> 'nonexistent' in flags
>>> flags.fake
class wtforms.fields.Label

On all fields, the label property is an instance of this class. Labels can be printed to yield a <label for="field_id">Label Text</label> HTML tag enclosure. Similar to fields, you can also call the label with additional html params.


The ID of the field which this label will reference.


The original label text passed to the field’s constructor.