Form handling and validation

Forms are validated in Glashammer using WTForms. The forms bundle in Glashammer does not have to be used, it only helps by adding some features that may help you in addition to WTForms.

Forms, Fields, and Validators

A form has any number of fields, and each of these fields has any number of validators. Fields are of different types that reflect the different types of data you wish to get from the request.

Creating a form

A form should first be defined as a class with a declarative syntax like so:

from wtforms import Form, TextField, PasswordField

class LoginForm(Form):
    """My login form"""
    username = TextField()
    password = PasswordField()

This form contains two fields, a username and a password.

Loading a form with request form data

The form above is just a definition of the form. To make it useful, the form should instantiated and loaded with form data.

This usually occurs during a request in a view callable, for example:

def do_login(request):
    form = LoginForm(request.form)

Using the form instance

A form instance can do a number of things. Firstly the form data passed on construction may be validated using the wtforms.Form.validate() method like so:

def do_login(request):
    form = LoginForm(request.form)
    if form.validate():
        # Form is valid
        pass

The form instance may also be used to populate a python instance, using the wtforms.Form.auto_populate() method. So using a slightly different example where this might make sense:

def do_comment(request):
    form = CommentForm(request.form)
    if form.validate():
        # Form is valid
        comment = Comment()
        form.auto_populate(comment)

Rendering form data in a template

The usual pattern is to pass the form instance into the template’s context during a glashammer.utils.render_response() call like so:

def do_comment(request):
    if request.method == 'GET':
        # it's a get, so just show the form
        form = CommentForm()
        return render_response('add_comment.html', form=form)

And thus the form instance will be available in the template.

From the template, a number of things can be accessed:

Rendering each field

A quick rendering of each field can be performed on the form by accessing the field by name, for example:

{{ form.username }}

This is the simple way. In reality it is actually calling the form.username() function. Any html parameter can be passed into this call, for example:

{{ form.password(style="width: 200px;" max_length=15) }}

Rendering each field label

The label for each field can also be accessed, with:

{{ form.username.label }}

Rendering an html label for use in the form.

Dict-like form access

Jinja2 allows you to use dict-like attribute markup, so if your field name is a variable, you can access it like:

{{ form[field_name] }}

Complete form example

So, for a complete form, we might have:

<form method="post" action="">
    {{ form.username.label }} {{ form.username }}
    {{ form.password.label }} {{ form.password }}
    <input type="submit" value="Log in" />
</form>

Note

There is nothing to stop you from hand-writing your form markup, and for more complicated forms you certainly will have to. The validation for the form stays the same though, and you have a nice graded path from automatic generation to hand-written.

Built in field types

Built in validators

Complete API

class wtforms.form.Form(formdata=None, obj=None, prefix='', idprefix='', **kwargs)

Form base class. Provides core behaviour like field construction, validation, and data and error proxying.

populate_obj(obj)

Populates the attributes of the passed obj with data from the form’s fields.

Note: This is a destructive operation, any attribute with the same name as a field will be overridden. Use with caution.

validate()

Validates the form by calling validate on each field, passing any extra Form.validate_<fieldname> validators to the field validator.

Returns True if no errors occur.

class wtforms.fields.BooleanField(label=u'', validators=None, **kwargs)
Represents an <input type="checkbox">.
class wtforms.fields.DecimalField(label=u'', validators=None, number_format='%0.2f', **kwargs)

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

Defining the number_format parameter to the constructor allows you to customize how the number is displayed, using standard python string formatting rules.

class wtforms.fields.DateTimeField(label=u'', validators=None, format='%Y-%m-%d %H:%M:%S', **kwargs)
Can be represented by one or multiple text-inputs.
class wtforms.fields.FieldList(unbound_field, label=u'', validators=None, min_entries=0, max_entries=None, default=(), **kwargs)

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

>>> authors = FieldList(TextField('Name', [validators.required()])) 
Parameters:
  • 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.
append_entry(data=<object object at 0x403aadd0>)
Create a new entry with optional default data
pop_entry()
Removes the last entry from the list and returns it.
class wtforms.fields.FileField(label=u'', validators=None, filters=(), description=u'', id=None, default=None, widget=None, _form=None, _name=None)
Can render a file-upload field. Will take any passed filename value, if any is sent by the browser in the post params. This field will NOT actually handle the file upload portion, as wtforms does not deal with individual frameworks’ file handling capabilities.
class wtforms.fields.FormField(form_class, label=u'', validators=None, **kwargs)

Encapsulate a form as a field in another form.

Parameters:
  • form_class – A subclass of Form that will be encapsulated.
class wtforms.fields.HiddenField(label=u'', validators=None, filters=(), description=u'', id=None, default=None, widget=None, _form=None, _name=None)
Represents an <input type="hidden">.
class wtforms.fields.IntegerField(label=u'', validators=None, **kwargs)
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.PasswordField(label=u'', validators=None, filters=(), description=u'', id=None, default=None, widget=None, _form=None, _name=None)
Represents an <input type="password">.
class wtforms.fields.RadioField(label=u'', validators=None, coerce=<type 'unicode'>, choices=None, **kwargs)

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.

class wtforms.fields.SelectMultipleField(label=u'', validators=None, coerce=<type 'unicode'>, choices=None, **kwargs)
No different from a normal select field, except this one can take (and validate) multiple choices. You’ll need to specify the HTML rows attribute to the select field when rendering.
class wtforms.fields.SubmitField(label=u'', validators=None, **kwargs)
Represents an <input type="submit">. This allows checking if a given submit button has been pressed.
class wtforms.fields.TextField(label=u'', validators=None, filters=(), description=u'', id=None, default=None, widget=None, _form=None, _name=None)
This field is the base for most of the more complicated fields, and represents an <input type="text">.
class wtforms.fields.TextAreaField(label=u'', validators=None, filters=(), description=u'', id=None, default=None, widget=None, _form=None, _name=None)
This field represents an HTML <textarea> and can be used to take multi-line input.
class wtforms.validators.Email(message=u'Invalid email address.')

Validates an email address. Note that this uses a very primitive regular expression and should only be used in instances where you later verify by other means, such as email activation or lookups.

Parameters:
  • message – Error message to raise in case of a validation error.
wtforms.validators.email
alias of Email
class wtforms.validators.EqualTo(fieldname, message=None)

Compares the values of two fields.

Parameters:
  • fieldname – The name of the other field to compare to.
  • message – Error message to raise in case of a validation error.
wtforms.validators.equal_to
alias of EqualTo
class wtforms.validators.IPAddress(message=u'Invalid IP address.')

Validates an IP(v4) address.

Parameters:
  • message – Error message to raise in case of a validation error.
wtforms.validators.ip_address
alias of IPAddress
class wtforms.validators.Length(min=-1, max=-1, message=None)

Validates the length of a string.

Parameters:
  • min – The minimum required length of the string. If not provided, minimum length will not be checked.
  • max – The maximum length of the string. If not provided, maximum length will not be checked.
  • message – Error message to raise in case of a validation error. A default containing min and max length is provided.
wtforms.validators.length
alias of Length
class wtforms.validators.Optional
Allows empty input and stops the validation chain from continuing.
wtforms.validators.optional
alias of Optional
class wtforms.validators.Required(message=u'This field is required.')

Validates that the field contains data. This validator will stop the validation chain on error.

Parameters:
  • message – Error message to raise in case of a validation error.
wtforms.validators.required
alias of Required
class wtforms.validators.Regexp(regex, flags=0, message=u'Invalid input.')

Validates the field against a user provided regexp.

Parameters:
  • regex – The regular expression string to use. Can also be a compiled regular expression pattern.
  • flags – The regexp flags to use, for example re.IGNORECASE. Ignored if regex is not a string.
  • message – Error message to raise in case of a validation error.
wtforms.validators.regexp
alias of Regexp
class wtforms.validators.URL(require_tld=True, message=u'Invalid URL.')

Simple regexp based url validation. Much like the email validator, you probably want to validate the url later by other means if the url must resolve.

Parameters:
  • require_tld – If true, then the domain-name portion of the URL must contain a .tld suffix. Set this to false if you want to allow domains like localhost.
  • message – Error message to raise in case of a validation error.
wtforms.validators.url
alias of URL