1. simplecodes
  2. Untitled project
  3. wtforms


wtforms / docs / forms.rst


Forms provide the highest level API in WTForms. They contain your field definitions, delegate validation, take input, aggregate errors, and in general function as the glue holding everything together.

The Form class

Declarative Form base class.




Defining Forms

To define a form, one makes a subclass of :class:`Form` and defines the fields declaratively as class attributes:

class MyForm(Form):
    first_name = StringField(u'First Name', validators=[validators.input_required()])
    last_name  = StringField(u'Last Name', validators=[validators.optional()])

Field names can be any valid python identifier, with the following restrictions:

  • Field names are case-sensitive.
  • Field names may not begin with "_" (underscore)
  • Field names may not begin with "validate"

Form Inheritance

Forms may subclass other forms as needed. The new form will contain all fields of the parent form, as well as any new fields defined on the subclass. A field name re-used on a subclass causes the new definition to obscure the original.

class PastebinEdit(Form):
    language = SelectField(u'Programming Language', choices=PASTEBIN_LANGUAGES)
    code     = TextAreaField()

class PastebinEntry(PastebinEdit):
    name = StringField(u'User Name')

In-line Validators

In order to provide custom validation for a single field without needing to write a one-time-use validator, validation can be defined inline by defining a method with the convention validate_fieldname:

class SignupForm(Form):
    age = IntegerField(u'Age')

    def validate_age(form, field):
        if field.data < 13:
            raise ValidationError("We're sorry, you must be 13 or older to register")

Using Forms

A form is most often constructed in the controller code for handling an action, with the form data wrapper from the framework passed to its constructor, and optionally an ORM object. A typical view begins something like:

def edit_article(request):
    article = Article.get(...)
    form = MyForm(request.POST, article)

A typical CRUD view has a user editing an object that needs various fields updated. The Form would have fields describing the fields to be updated and the validation rules, where the attribute names of the fields match those of the attribute names on the object. The second parameter to the Form, the obj parameter, is used to populate form defaults on the initial view.


While we did pass an object as the data source, this object data is only used if there is no POST data. If there is any POST data at all, then the object data is ignored. This is done for security and consistency reasons.

This pattern is mostly a convenience since most application controllers don't separate GET and POST requests into separate view methods.

The constructed form can then validate any input data and generate errors if invalid. Typically, the validation pattern in the view looks like:

if request.POST and form.validate():
    return redirect('/articles')

Note that we have it so :meth:`~Form.validate` is only called if there is POST data. The reason we gate the validation check this way is that when there is no POST data (such as in a typical CRUD form) we don't want to cause validation errors.

Inside the gated block, we call :meth:`~Form.populate_obj` to copy the data onto fields on the 'article' object. We also then redirect after a successful completion. The reason we redirect after the post is a best-practice associated with the Post/Redirect/Get design pattern.

If there is no POST data, or the data fails to validate, then the view "falls through" to the rendering portion. The Form object can be passed into the template and its attributes can be used to render the fields and also for displaying errors:

return render('edit.html', form=form, article=article)

So there we have a full simple "edit object" page setup which illustrates a best-practice way of using WTForms. This is by no means the only way to use WTForms, but just an illustration of how the various features work.

Here is the full code for the view we just made:

def edit_article(request):
    article = Article.get(...)
    form = MyForm(request.POST, article)

    if request.POST and form.validate():
        return redirect('/articles')

    return render('edit.html', form=form, article=article)

Low-Level API


This section is provided for completeness; and is aimed at authors of complementary libraries and those looking for very special behaviors. Don't use BaseForm unless you know exactly why you are using it.

For those looking to customize how WTForms works, for libraries or special applications, it might be worth using the :class:`BaseForm` class. BaseForm is the parent class of :class:`Form`, and most of the implementation logic from Form is actually handled by BaseForm.

The major difference on the surface between BaseForm and Form is that fields are not defined declaratively on a subclass of BaseForm. Instead, you must pass a dict of fields to the constructor. Likewise, you cannot add fields by inheritance. In addition, BaseForm does not provide: sorting fields by definition order, or inline validate_foo validators. Because of this, for the overwhelming majority of uses we recommend you use Form instead of BaseForm in your code.

What BaseForm provides is a container for a collection of fields, which it will bind at instantiation, and hold in an internal dict. Dict-style access on a BaseForm instance will allow you to access (and modify) the enclosed fields.