Source

wtforms / docs / fields.rst

Full commit

Fields

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 :class:`SelectField`) can also take additional field-specific keyword arguments. Consult the built-in fields reference for information on those.

The Field base class

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.

Construction

Validation

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.

Data access and processing

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

Rendering

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.

Properties

Basic fields

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

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 = [(g.id, g.name) for g in Group.query.order_by('name')]

Note we didn't pass a choices to the :class:`~wtforms.fields.SelectField` constructor, but rather created the list in the view function. Also, the coerce keyword arg to :class:`~wtforms.fields.SelectField` says that we use :func:`int()` to coerce form data. The default coerce is :func:`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=.

Convenience Fields

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.

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):
        if self.data:
            return u', '.join(self.data)
        else:
            return u''

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

The _value method is called by the :class:`~wtforms.widgets.TextInput` widget to provide the value that is displayed in the form. Overriding the :meth:`~Field.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:
            self.data = list(self._remove_duplicates(self.data))

    @classmethod
    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 :meth:`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

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.