Edit me on GitHub

API Documentation

Form-Related

class deform.Field(schema, renderer=None, counter=None, resource_registry=None, appstruct=<colander.null>, **kw)

Represents an individual form field (a visible object in a form rendering).

A deform.form.Field object instance is meant to last for the duration of a single web request. As a result, a field object is often used as a scratchpad by the widget associated with that field. Using a field as a scratchpad makes it possible to build implementations of state-retaining widgets while instances of those widget still only need to be constructed once instead of on each request.

Attributes

schema
The schema node associated with this field.
widget
The widget associated with this field. When no widget is defined in the schema node, a default widget will be created. The default widget will have a generated item_css_class containing the normalized version of the name attribute (with item prepended, e.g. item-username).
order
An integer indicating the relative order of this field’s construction to its children and parents.
oid
A string incorporating the order attribute that can be used as a unique identifier in HTML code (often for id attributes of field-related elements). A default oid is generated that looks like this: deformField0. A custom oid can provided, but if the field is cloned, the clones will get unique default oids.
name
An alias for self.schema.name
title
An alias for self.schema.title
description
An alias for self.schema.description
required
An alias for self.schema.required
typ
An alias for self.schema.typ
children
Child fields of this field.
error
The exception raised by the last attempted validation of the schema element associated with this field. By default, this attribute is None. If non-None, this attribute is usually an instance of the exception class colander.Invalid, which has a msg attribute providing a human-readable validation error message.
errormsg
The msg attribute of the error attached to this field or None if the error attached to this field is None.
renderer
The template renderer associated with the form. If a renderer is not passed to the constructor, the default deform renderer will be used (the default renderer).
counter
None or an instance of itertools.counter which is used to generate sequential order-related attributes such as oid and order.
resource_registry
The resource registry associated with this field.

Constructor Arguments

renderer, counter, resource_registry and appstruct are accepted as explicit keyword arguments to the deform.Field. These are also available as attribute values. renderer, if passed, is a template renderer as described in Using an alternative templating system. counter, if passed, should be an itertools.counter object (useful when rendering multiple forms on the same page, see http://deformdemo.repoze.org/multiple_forms/. resource_registry, if passed should be a widget resource registry (see also The (High-Level) deform.Field.get_widget_resources() Method).

If any of these values is not passed, a suitable default values is used in its place.

The appstruct constructor argument is used to prepopulate field values related to this form’s schema. If an appstruct is not supplied, the form’s fields will be rendered with default values unless an appstruct is supplied to the render method explicitly.

The deform.Field constructor also accepts arbitrary keyword arguments. When an ‘unknown’ keyword argument is passed, it is attached unmolested to the form field as an attribute.

All keyword arguments (explicit and unknown) are also attached to all children nodes of the field being constructed.

__getitem__(name)

Return the subfield of this field named name or raise a KeyError if a subfield does not exist named name.

__iter__()

Iterate over the children fields of this field.

__contains__(name)
translate(msgid)

Use the translator passed to the renderer of this field to translate the msgid into a term and return the term. If the renderer does not have a translator, this method will return the msgid.

clone()

Clone the field and its subfields, retaining attribute information. Return the cloned field. The order attribute of the node is not cloned; instead the field receives a new order attribute; it will be a number larger than the last renderered field of this set.

deserialize(pstruct)

Deserialize the pstruct into a cstruct and return the cstruct.

end_mapping(name=None)

Create an end-mapping tag (a literal). If name is None, the name of this node will be used to generate the name in the tag. See the Peppercorn documentation for more information.

end_rename(name=None)

Create a start-rename tag (a literal). If name is None, the name of this node will be used to generate the name in the tag. See the Peppercorn documentation for more information.

end_sequence(name=None)

Create an end-sequence tag (a literal). If name is None, the name of this node will be used to generate the name in the tag. See the Peppercorn documentation for more information.

errormsg

Return the msg attribute of the error attached to this field. If the error attribute is None, the return value will be None.

get_widget_requirements()

Return a sequence of two tuples in the form [(requirement_name, version), ..].

The first element in each two-tuple represents a requirement name. When a requirement name is returned as part of get_widget_requirements, it means that one or more CSS or Javascript resources need to be loaded by the page performing the form rendering in order for some widget on the page to function properly.

The second element in each two-tuple is the reqested version of the library resource. It may be None, in which case the version is unspecified.

See also the requirements attribute of deform.Widget and the explanation of widget requirements in The (Low-Level) deform.Field.get_widget_requirements() Method.

get_widget_resources(requirements=None)

Return a resources dictionary in the form {'js':[seq], 'css':[seq]}. js represents Javascript resources, css represents CSS resources. seq represents a sequence of resource paths. Each path in seq represents a relative resource name, as defined by the mapping of a requirement to a set of resource specification by the resource registry attached to this field or form.

This method may raise a ValueError if the resource registry associated with this field or form cannot resolve a requirement to a set of resource paths.

The requirements argument represents a set of requirements as returned by a manual call to deform.Field.get_widget_requirements(). If requirements is not supplied, the requirement are implied by calling the deform.Field.get_widget_requirements() method against this form field.

See also The (High-Level) deform.Field.get_widget_resources() Method.

render(appstruct=(Default), **kw)

Render the field (or form) to HTML using appstruct as a set of default values and returns the HTML string. appstruct is typically a dictionary of application values matching the schema used by this form, or colander.null to render all defaults. If it is omitted, the rendering will use the appstruct passed to the constructor.

Calling this method passing an appstruct is the same as calling:

cstruct = form.set_appstruct(appstruct)
form.serialize(cstruct, **kw)

Calling this method without passing an appstruct is the same as calling:

cstruct = form.cstruct
form.serialize(cstruct, **kw)

See the documentation for colander.SchemaNode.serialize() and deform.widget.Widget.serialize() .

Note

Deform versions before 0.9.8 only accepted a readonly keyword argument to this function. Version 0.9.8 and later accept arbitrary keyword arguments.

render_template(template, **kw)

Render the template named template using kw as the top-level keyword arguments (augmented with field and cstruct if necessary)

serialize(cstruct=(Default), **kw)

Serialize the cstruct into HTML and return the HTML string. This function just turns around and calls self.widget.serialize(**kw); therefore the field widget’s serialize method should be expecting any values sent in kw. If cstruct is not passed, the cstruct attached to this node will be injected into kw as cstruct. If field is not passed in kw, this field will be injected into kw as field.

Note

Deform versions before 0.9.8 only accepted a readonly keyword argument to this function. Version 0.9.8 and later accept arbitrary keyword arguments. It also required that cstruct was passed; it’s broken out from kw in the method signature for backwards compatibility.

set_appstruct(appstruct)

Set the cstruct of this node (and its child nodes) using appstruct as input.

classmethod set_default_renderer(renderer)

Set the callable that will act as a default renderer for instances of the associated class when no renderer argument is provided to the class’ constructor. Useful when you’d like to use an alternate templating system.

Calling this method resets the default renderer.

classmethod set_default_resource_registry(registry)

Set the callable that will act as a default resource registry for instances of the associated class when no resource_registry argument is provided to the class’ constructor. Useful when you’d like to use non-default requirement to resource path mappings for the entirety of a process.

Calling this method resets the default resource registry.

set_pstruct(pstruct)

Set the cstruct of this node (and its child nodes) using pstruct as input.

set_widgets(values, separator='.')

set widgets of the child fields of this field or form element. widgets should be a dictionary in the form:

{'dotted.field.name':Widget(),
 'dotted.field.name2':Widget()}

The keys of the dictionary are dotted names. Each dotted name refers to a single field in the tree of fields that are children of the field or form object upon which this method is called.

The dotted name is split on its dots and the resulting list of names is used as a search path into the child fields of this field in order to find a field to which to assign the associated widget.

Two special cases exist:

  • If the key is the empty string (''), the widget is assigned to the field upon which this method is called.
  • If the key contains an asterisk as an element name, the first child of the found element is traversed. This is most useful for sequence fields, because the first (and only) child of sequence fields is always the prototype field which is used to render all fields in the sequence within a form rendering.

If the separator argument is passed, it is should be a string to be used as the dot character when splitting the dotted names (useful for supplying if one of your field object has a dot in its name, and you need to use a different separator).

Examples follow. If the following form is used:

class Person(Schema):
    first_name = SchemaNode(String())
    last_name = SchemaNode(String())

class People(SequenceSchema):
    person = Person()

class Conference(Schema):
    people = People()
    name = SchemaNode(String())

schema = Conference()
form = Form(schema)

The following invocations will have the following results against the schema defined above:

form.set_widgets({'people.person.first_name':TextAreaWidget()})

Set the first_name field’s widget to a TextAreaWidget.

form.set_widgets({'people.*.first_name':TextAreaWidget()})

Set the first_name field’s widget to a TextAreaWidget.

form.set_widgets({'people':MySequenceWidget()})

Set the people sequence field’s widget to a MySequenceWidget.

form.set_widgets({'people.*':MySequenceWidget()})

Set the person field’s widget to a MySequenceWidget.

form.set_widgets({'':MyMappingWidget()})

Set form node’s widget to a MyMappingWidget.
classmethod set_zpt_renderer(search_path, auto_reload=True, debug=True, encoding='utf-8', translator=None)

Create a Chameleon ZPT renderer that will act as a default renderer for instances of the associated class when no renderer argument is provided to the class’ constructor. The arguments to this classmethod have the same meaning as the arguments provided to a deform.ZPTRendererFactory.

Calling this method resets the default renderer.

This method is effectively a shortcut for cls.set_default_renderer(ZPTRendererFactory(...)).

start_mapping(name=None)

Create a start-mapping tag (a literal). If name is None, the name of this node will be used to generate the name in the tag. See the Peppercorn documentation for more information.

start_rename(name=None)

Create a start-rename tag (a literal). If name is None, the name of this node will be used to generate the name in the tag. See the Peppercorn documentation for more information.

start_sequence(name=None)

Create a start-sequence tag (a literal). If name is None, the name of this node will be used to generate the name in the tag. See the Peppercorn documentation for more information.

translate(msgid)

Use the translator passed to the renderer of this field to translate the msgid into a term and return the term. If the renderer does not have a translator, this method will return the msgid.

validate(controls, subcontrol=None)

Validate the set of controls returned by a form submission against the schema associated with this field or form. controls should be a document-ordered sequence of two-tuples that represent the form submission data. Each two-tuple should be in the form (key, value). node should be the schema node associated with this widget.

For example, using WebOb, you can compute a suitable value for controls via:

request.POST.items()

Or, if you’re using a cgi.FieldStorage object named fs, you can compute a suitable value for controls via:

controls = []
if fs.list:
    for control in fs.list:
        if control.filename:
            controls.append((control.name, control))
        else:
            controls.append((control.name, control.value))

Equivalent ways of computing controls should be available to any web framework.

When the validate method is called:

  • if the fields are successfully validated, a data structure represented by the deserialization of the data as per the schema is returned. It will be a mapping.
  • If the fields cannot be successfully validated, a deform.exception.ValidationFailure exception is raised.

The typical usage of validate in the wild is often something like this (at least in terms of code found within the body of a pyramid view function, the particulars will differ in your web framework):

from webob.exc import HTTPFound
from deform.exception import ValidationFailure
from deform import Form
import colander

from my_application import do_something

class MySchema(colander.MappingSchema):
    color = colander.SchemaNode(colander.String())

schema = MySchema()

def view(request):
    form = Form(schema, buttons=('submit',))
    if 'submit' in request.POST:  # form submission needs validation
        controls = request.POST.items()
        try:
            deserialized = form.validate(controls)
            do_something(deserialized)
            return HTTPFound(location='http://example.com/success')
        except ValidationFailure as e:
            return {'form':e.render()}
    else:
        return {'form':form.render()} # the form just needs rendering

Warning

form.validate(controls) mutates the form instance, so the form instance should be constructed (and live) inside one request.

If subcontrol is supplied, it represents a named subitem in the data returned by peppercorn.parse(controls). Use this subitem as the pstruct to validate instead of using the entire result of peppercorn.parse(controls) as the pstruct to validate. For example, if you’ve embedded a mapping in the form named user, and you want to validate only the data contained in that mapping instead if all of the data in the form post, you might use form.validate(controls, subcontrol='user').

validate_pstruct(pstruct)

Validate the pstruct passed. Works exactly like the deform.field.validate method, except it accepts a pstruct instead of a set of form controls. A usage example follows:

if 'submit' in request.POST:  # the form submission needs validation
    controls = request.POST.items()
    pstruct = peppercorn.parse(controls)
    substruct = pstruct['submapping']
    try:
        deserialized = form.validate_pstruct(substruct)
        do_something(deserialized)
        return HTTPFound(location='http://example.com/success')
    except ValidationFailure, e:
        return {'form':e.render()}
else:
    return {'form':form.render()} # the form just needs rendering
class deform.Form(schema, action='', method='POST', buttons=(), formid='deform', use_ajax=False, ajax_options='{}', autocomplete=None, **kw)

Field representing an entire form.

Arguments:

schema
A colander.SchemaNode object representing a schema to be rendered. Required.
action
The form action (inserted into the action attribute of the form’s form tag when rendered). Default: the empty string.
method
The form method (inserted into the method attribute of the form’s form tag when rendered). Default: POST.
buttons
A sequence of strings or deform.form.Button objects representing submit buttons that will be placed at the bottom of the form. If any string is passed in the sequence, it is converted to deform.form.Button objects.
formid
The identifier for this form. This value will be used as the HTML id attribute of the rendered HTML form. It will also be used as the value of a hidden form input control (__formid__) which will be placed in this form’s rendering. You should pass a string value for formid when more than one Deform form is placed into a single page and both share the same action. When one of the forms on the page is posted, your code will to be able to decide which of those forms was posted based on the differing values of __formid__. By default, formid is deform.
autocomplete
Controls this form’s autocomplete attribute. If autocomplete is None, no autocomplete attribute will be added to the form tag. If autocomplete is a true value, an autocomplete='on' attribute will be added to the form tag. If autocomplete is a false value, an autocomplete='off' attribute will be added to the form tag. Default: None.
use_ajax
If this option is True, the form will use AJAX (actually AJAH); when any submit button is clicked, the DOM node related to this form will be replaced with the result of the form post caused by the submission. The page will not be reloaded. This feature uses the jquery.form library ajaxForm feature as per http://jquery.malsup.com/form/. Default: False. If this option is True, the jquery.form.js library must be loaded in the HTML page which embeds the form. A copy of it exists in the static directory of the deform package.
ajax_options

A string which must represent a JavaScript obejct (dictionary) of extra AJAX options as per http://jquery.malsup.com/form/#options-object. For example:

'{"success": function (rText, sText, xhr, form) {alert(sText)};}'

Default options exist even if ajax_options is not provided. By default, target points at the DOM node representing the form and and replaceTarget is true.

A successhandler calls the deform.processCallbacks method that will ajaxify the newly written form again. If you pass these values in ajax_options, the defaults will be overridden. If you want to override the success handler, don’t forget to call deform.processCallbacks, otherwise subsequent form submissions won’t be submitted via AJAX.

This option has no effect when use_ajax is False.

The default value of ajax_options is a string representation of the empty object.

The deform.Form constructor also accepts all the keyword arguments accepted by the deform.Field class. These keywords mean the same thing in the context of a Form as they do in the context of a Field (a Form is just another kind of Field).

class deform.Button(name='submit', title=None, type='submit', value=None, disabled=False, css_class=None)

A class representing a form submit button. A sequence of deform.widget.Button objects may be passed to the constructor of a deform.form.Form class when it is created to represent the buttons renderered at the bottom of the form.

Arguments:

name
The string or unicode value used as the name of the button when rendered (the name attribute of the button or input tag resulting from a form rendering). Default: submit.
title
The value used as the title of the button when rendered (shows up in the button inner text). Default: capitalization of whatever is passed as name. E.g. if name is passed as submit, title will be Submit.
type
The value used as the type of button. The HTML spec supports submit, reset and button. Default: submit.
value
The value used as the value of the button when rendered (the value attribute of the button or input tag resulting from a form rendering). Default: same as name passed.
disabled
Render the button as disabled if True.
css_class
The name of a CSS class to attach to the button. In the default form rendering, this string will be appended to btnText submit to become part of the class attribute of the button. For example, if css_class was foobar then the resulting default class becomes btnText submit foobar. Default: None (no additional class).

Widget-Related

class deform.widget.Widget(**kw)

A widget is the building block for rendering logic. The deform.widget.Widget class is never instantiated directly: it is the abstract class from which all other widget types within deform.widget derive. It should likely also be subclassed by application-developer-defined widgets.

A widget instance is attached to a field during normal operation. A widget is not meant to carry any state. Instead, widget implementations should use the field object passed to them during deform.widget.Widget.serialize() and deform.widget.Widget.deserialize() as a scratchpad for state information.

All widgets have the following attributes:

hidden
An attribute indicating the hidden state of this widget. The default is False. If this attribute is not False, the field associated with this widget will not be rendered in the form (although, if the widget is a structural widget, its children will be; hidden is not a recursive flag). No label, no error message, nor any furniture such as a close button when the widget is one of a sequence will exist for the field in the rendered form.
readonly
If this attribute is true, the readonly rendering of the widget should be output during HTML serialization.
category
A string value indicating the category of this widget. This attribute exists to inform structural widget rendering behavior. For example, when a text widget or another simple ‘leaf-level’ widget is rendered as a child of a mapping widget using the default template mapping template, the field title associated with the child widget will be rendered above the field as a label by default. This is because simple child widgets are in the default category and no special action is taken when a structural widget renders child widgets that are in the default category. However, if the default mapping widget encounters a child widget with the category of structural during rendering (the default mapping and sequence widgets are in this category), it omits the title. Default: default
error_class
The name of the CSS class attached to various tags in the form renderering indicating an error condition for the field associated with this widget. Default: error.
css_class
The name of the CSS class attached to various tags in the form renderering specifying a new class for the field associated with this widget. Default: None (no class).
item_css_class
The name of the CSS class attached to the li which surrounds the field when it is rendered inside the mapping_item or sequence_item template.
requirements

A sequence of two-tuples in the form ( (requirement_name, version_id), ...) indicating the logical external requirements needed to make this widget render properly within a form. The requirement_name is a string that logically (not concretely, it is not a filename) identifies one or more Javascript or CSS resources that must be included in the page by the application performing the form rendering. The requirement name string value should be interpreted as a logical requirement name (e.g. jquery for JQuery, ‘tinymce’ for Tiny MCE). The version_id is a string indicating the version number (or None if no particular version is required). For example, a rich text widget might declare requirements = (('tinymce', '3.3.8'),). See also: Specifying Widget Requirements and Widget Requirements and Resources.

Default: () (the empty tuple, meaning no special requirements).

These attributes are also accepted as keyword arguments to all widget constructors; if they are passed, they will override the defaults.

Particular widget types also accept other keyword arguments that get attached to the widget as attributes. These are documented as ‘Attributes/Arguments’ within the documentation of each concrete widget implementation subclass.

deserialize(field, pstruct)

The deserialize method of a widget must deserialize a pstruct value to a cstruct value and return the cstruct value. The pstruct argument is a value resulting from the parse method of the Peppercorn package. The field argument is the field object to which this widget is attached.

handle_error(field, error)

The handle_error method of a widget must:

  • Set the error attribute of the field object it is passed, if the error attribute has not already been set.
  • Call the handle_error method of each subfield which also has an error (as per the error argument’s children attribute).
serialize(field, cstruct, **kw)

The serialize method of a widget must serialize a cstruct value to an HTML rendering. A cstruct value is the value which results from a Colander schema serialization for the schema node associated with this widget. serialize should return the HTML rendering: the result of this method should always be a string containing HTML. The field argument is the field object to which this widget is attached. The **kw argument allows a caller to pass named arguments that might be used to influence individual widget renderings.

class deform.widget.TextInputWidget(**kw)

Renders an <input type="text"/> widget.

Attributes/Arguments

size
The size, in columns, of the text input field. Defaults to None, meaning that the size is not included in the widget output (uses browser default size).
template
The template name used to render the widget. Default:
textinput.
readonly_template
The template name used to render the widget in read-only mode. Default: readonly/textinput.
strip
If true, during deserialization, strip the value of leading and trailing whitespace (default True).
style
A string that will be placed literally in a style attribute on the text input tag. For example, ‘width:150px;’. Default: None, meaning no style attribute will be added to the input tag.
mask

A jquery.maskedinput input mask, as a string.

a - Represents an alpha character (A-Z,a-z) 9 - Represents a numeric character (0-9) * - Represents an alphanumeric character (A-Z,a-z,0-9)

All other characters in the mask will be considered mask literals.

Example masks:

Date: 99/99/9999

US Phone: (999) 999-9999

US SSN: 999-99-9999

When this option is used, the jquery.maskedinput library must be loaded into the page serving the form for the mask argument to have any effect. See Using Text Input Masks.

mask_placeholder
The placeholder for required nonliteral elements when a mask is used. Default: _ (underscore).
class deform.widget.MoneyInputWidget(**kw)

Renders an <input type="text"/> widget with Javascript which enforces a valid currency input. It should be used along with the colander.Decimal schema type (at least if you care about your money). This widget depends on the jquery-maskMoney JQuery plugin.

Attributes/Arguments

size
The size, in columns, of the text input field. Defaults to None, meaning that the size is not included in the widget output (uses browser default size).
template
The template name used to render the widget. Default:
moneyinput.
readonly_template
The template name used to render the widget in read-only mode. Default: readonly/textinput.
style
A string that will be placed literally in a style attribute on the text input tag. For example, ‘width:150px;’. Default: None, meaning no style attribute will be added to the input tag.
options

A dictionary or sequence of two-tuples containing jquery-maskMoney options. The valid options are:

symbol
the symbol to be used before of the user values. default: $
showSymbol
set if the symbol must be displayed or not. default: False
symbolStay
set if the symbol will stay in the field after the user exists the field. default: False
thousands
the thousands separator. default: ,
decimal
the decimal separator. default: .
precision
how many decimal places are allowed. default: 2
defaultZero
when the user enters the field, it sets a default mask using zero. default: True
allowZero
use this setting to prevent users from inputing zero. default: False
allowNegative
use this setting to prevent users from inputing negative values. default: False
class deform.widget.AutocompleteInputWidget(**kw)

Renders an <input type="text"/> widget which provides autocompletion via a list of values.

When this option is used, the jquery.ui.autocomplete library must be loaded into the page serving the form for autocompletion to have any effect. See also Using the AutocompleteInputWidget. A version of JQuery UI which includes the autoinclude sublibrary is included in the deform static directory. The default styles for JQuery UI are also available in the deform static/css directory.

Attributes/Arguments

size
The size, in columns, of the text input field. Defaults to None, meaning that the size is not included in the widget output (uses browser default size).
template
The template name used to render the widget. Default: autocomplete_input.
readonly_template
The template name used to render the widget in read-only mode. Default: readonly/textinput.
strip
If true, during deserialization, strip the value of leading and trailing whitespace (default True).
values

values from which jquery.ui.autocomplete provides autocompletion. It MUST be an iterable that can be converted to a json array by [simple]json.dumps. It is also possible to pass a [base]string representing a remote URL.

If values is a string it will be treated as a URL. If values is an iterable which can be serialized to a json array, it will be treated as local data.

If a string is provided to a URL, an xhr request will be sent to the URL. The response should be a JSON serialization of a list of values. For example:

[‘foo’, ‘bar’, ‘baz’]

Defaults to None.

min_length
min_length is an optional argument to jquery.ui.autocomplete. The number of characters to wait for before activating the autocomplete call. Defaults to 2.
delay
delay is an optional argument to jquery.ui.autocomplete. It sets the time to wait after a keypress to activate the autocomplete call. Defaults to 10 ms or 400 ms if a url is passed.
style
A string that will be placed literally in a style attribute on the text input tag. For example, ‘width:150px;’. Default: None, meaning no style attribute will be added to the input tag.
class deform.widget.HiddenWidget(**kw)

Renders an <input type="hidden"/> widget.

Attributes/Arguments

template
The template name used to render the widget. Default: hidden.
class deform.widget.TextAreaWidget(**kw)

Renders a <textarea> widget.

Attributes/Arguments

cols
The size, in columns, of the text input field. Defaults to None, meaning that the cols is not included in the widget output (uses browser default cols).
rows
The size, in rows, of the text input field. Defaults to None, meaning that the rows is not included in the widget output (uses browser default cols).
style
A string that will be placed literally in a style attribute on the textarea input tag. For example, ‘width:150px;’. Default: None, meaning no style attribute will be added to the input tag.
template
The template name used to render the widget. Default: textarea.
readonly_template
The template name used to render the widget in read-only mode. Default: readonly/textarea.
strip
If true, during deserialization, strip the value of leading and trailing whitespace (default True).
class deform.widget.RichTextWidget(**kw)

Renders a <textarea> widget with the TinyMCE Editor.

To use this widget the TinyMCE Editor library must be provided in the page where the widget is rendered. A version of TinyMCE Editor is included in Deform’s static directory.

Attributes/Arguments

readonly_template
The template name used to render the widget in read-only mode. Default: readonly/richtext.
delayed_load
If you have many richtext fields, you can set this option to True, and the richtext editor will only be loaded upon the user clicking the field. Default: False.
strip
If true, during deserialization, strip the value of leading and trailing whitespace. Default: True.
template
The template name used to render the widget. Default: richtext.
options

A dictionary or sequence of two-tuples containing additional options to pass to the TinyMCE init function call. All types within such structure should be Python native as the structure will be converted to JSON on serialization. This widget provides some sensible defaults, as described below in default_options.

You should refer to the TinyMCE Configuration documentation for details regarding all available configuration options.

The language option is passed to TinyMCE within the default template, using i18n machinery to determine the language to use. This option can be overriden if it is specified here in options.

Note: the elements option for TinyMCE is set automatically according to the given field’s oid.

Default: None (no additional options)

default_options = (('height', 240), ('width', 500), ('skin', 'default'), ('theme', 'simple'), ('mode', 'exact'), ('strict_loading_mode', True), ('theme_advanced_resizing', True), ('theme_advanced_toolbar_align', 'left'), ('theme_advanced_toolbar_location', 'top'))

Default options passed to TinyMCE. Customise by using options.

options = None

Options to pass to TinyMCE that will override default_options.

class deform.widget.CheckboxWidget(**kw)

Renders an <input type="checkbox"/> widget.

Attributes/Arguments

true_val
The value which should be returned during deserialization if the box is checked. Default: true.
false_val
The value which should be returned during deserialization if the box was left unchecked. Default: false.
template
The template name used to render the widget. Default: checkbox.
readonly_template
The template name used to render the widget in read-only mode. Default: readonly/checkbox.
class deform.widget.CheckedInputWidget(**kw)

Renders two text input fields: ‘value’ and ‘confirm’. Validates that the ‘value’ value matches the ‘confirm’ value.

Attributes/Arguments

template
The template name used to render the widget. Default: checked_input.
readonly_template
The template name used to render the widget in read-only mode. Default: readonly/checked_input.
size
The size attribute of the input fields (default: None, default browser size).
mismatch_message
The message to be displayed when the value in the primary field doesn’t match the value in the confirm field.
mask

A jquery.maskedinput input mask, as a string. Both input fields will use this mask.

a - Represents an alpha character (A-Z,a-z) 9 - Represents a numeric character (0-9) * - Represents an alphanumeric character (A-Z,a-z,0-9)

All other characters in the mask will be considered mask literals.

Example masks:

Date: 99/99/9999

US Phone: (999) 999-9999

US SSN: 999-99-9999

When this option is used, the jquery.maskedinput library must be loaded into the page serving the form for the mask argument to have any effect. See Using Text Input Masks.

mask_placeholder
The placeholder for required nonliteral elements when a mask is used. Default: _ (underscore).
class deform.widget.CheckedPasswordWidget(**kw)

Renders two password input fields: ‘password’ and ‘confirm’. Validates that the ‘password’ value matches the ‘confirm’ value.

Attributes/Arguments

template
The template name used to render the widget. Default: checked_password.
readonly_template
The template name used to render the widget in read-only mode. Default: readonly/checked_password.
size
The size attribute of the password input field (default: None).
class deform.widget.CheckboxChoiceWidget(**kw)

Renders a sequence of <input type="check"/> buttons based on a predefined set of values.

Attributes/Arguments

values
A sequence of two-tuples (the first value must be of type string, unicode or integer, the second value must be string or unicode) indicating allowable, displayed values, e.g. ( ('true', 'True'), ('false', 'False') ). The first element in the tuple is the value that should be returned when the form is posted. The second is the display value.
template
The template name used to render the widget. Default: checkbox_choice.
readonly_template
The template name used to render the widget in read-only mode. Default: readonly/checkbox_choice.
null_value
The value used to replace the colander.null value when it is passed to the serialize or deserialize method. Default: the empty string.
class deform.widget.OptGroup(label, *options)

Used in the values argument passed to an instance of SelectWidget to render an <optgroup> HTML tag.

Attributes/Arguments

label
The label of the <optgroup> HTML tag.
options
A sequence that describes the <options> HTML tag(s). It must have the same structure as the values argument/parameter in the SelectWidget class, but should not contain OptGroup instances since <optgroup> HTML tags cannot be nested.
class deform.widget.SelectWidget(**kw)

Renders <select> field based on a predefined set of values.

Attributes/Arguments

values

A sequence of items where each item must be either:

  • a two-tuple (the first value must be of type string, unicode or integer, the second value must be string or unicode) indicating allowable, displayed values, e.g. ('jsmith', 'John Smith'). The first element in the tuple is the value that should be returned when the form is posted. The second is the display value;
  • or an instance of optgroup_class (which is deform.widget.OptGroup by default).
size
The size attribute of the select input field (default: None).
null_value
The value which represents the null value. When the null value is encountered during serialization, the colander.null sentinel is returned to the caller. Default: '' (the empty string).
template
The template name used to render the widget. Default: select.
readonly_template
The template name used to render the widget in read-only mode. Default: readonly/select.
multiple
Enable multiple on the select widget ( default: False )
optgroup_class
The class used to represent <optgroup> HTML tags. Default: deform.widget.OptGroup.
long_label_generator

A function that returns the “long label” used as the description for very old browsers that do not support the <optgroup> HTML tag. If a function is provided, the label attribute will receive the (short) description, while the content of the <option> tag will receive the “long label”. The function is called with two parameters: the group label and the option (short) description.

For example, with the following widget:

long_label_gener = lambda group, label: ' - '.join((group, label))
SelectWidget(
  values=(
    ('', 'Select your favorite musician'),
    OptGroup('Guitarists',
             ('page', 'Jimmy Page'),
             ('hendrix', 'Jimi Hendrix')),
    OptGroup('Drummers',
            ('cobham', 'Billy Cobham'),
            ('bonham', 'John Bonham'))),
  long_label_generator=long_label_gener)

... the rendered options would look like:

<option value="">Select your favorite musician</option>
<optgroup label="Guitarists">
  <option value="page"
      label="Jimmy Page">Guitarists - Jimmy Page</option>
  <option value="hendrix"
      label="Jimi Hendrix">Guitarists - Jimi Hendrix</option>
</optgroup>
<optgroup label="Drummers">
  <option value="cobham"
      label="Billy Cobham">Drummers - Billy Cobham</option>
  <option value="bonham"
      label="John Bonham">Drummers - John Bonham</option>
</optgroup>

Default: None (which means that the label attribute is not rendered).

class deform.widget.RadioChoiceWidget(**kw)

Renders a sequence of <input type="radio"/> buttons based on a predefined set of values.

Attributes/Arguments

values
A sequence of two-tuples (the first value must be of type string, unicode or integer, the second value must be string or unicode) indicating allowable, displayed values, e.g. ( ('true', 'True'), ('false', 'False') ). The first element in the tuple is the value that should be returned when the form is posted. The second is the display value.
template
The template name used to render the widget. Default: radio_choice.
readonly_template
The template name used to render the widget in read-only mode. Default: readonly/radio_choice.
null_value
The value used to replace the colander.null value when it is passed to the serialize or deserialize method. Default: the empty string.
class deform.widget.MappingWidget(**kw)

Renders a mapping into a set of fields.

Attributes/Arguments

template
The template name used to render the widget. Default: mapping.
readonly_template
The template name used to render the widget in read-only mode. Default: readonly/mapping.
item_template
The template name used to render each item in the mapping. Default: mapping_item.
readonly_item_template
The template name used to render each item in the form. Default: readonly/mapping_item.
class deform.widget.SequenceWidget(**kw)

Renders a sequence (0 .. N widgets, each the same as the other) into a set of fields.

Attributes/Arguments

template
The template name used to render the widget. Default: sequence.
readonly_template
The template name used to render the widget in read-only mode. Default: readonly/sequence.
item_template
The template name used to render each value in the sequence. Default: sequence_item.
add_subitem_text_template

The string used as the add link text for the widget. Interpolation markers in the template will be replaced in this string during serialization with a value as follows:

${subitem_title}
The title of the subitem field
${subitem_description}
The description of the subitem field
${subitem_name}
The name of the subitem field

Default: Add ${subitem_title}.

render_initial_item
Deprecated boolean attribute indicating whether, on the first rendering of a form including this sequence widget, a single child widget rendering should be performed. Default: False. This attribute is honored for backwards compatibility only: in new applications, please use min_len=1 instead.
min_len
Integer indicating minimum number of acceptable subitems. Default: None (meaning no minimum). On the first rendering of a form including this sequence widget, at least this many subwidgets will be rendered. The JavaScript sequence management will not allow fewer than this many subwidgets to be present in the sequence.
max_len
Integer indicating maximum number of acceptable subwidgets. Default: None (meaning no maximum). The JavaScript sequence management will not allow more than this many subwidgets to be added to the sequence.
orderable
Boolean indicating whether the Javascript sequence management will allow the user to explicitly re-order the subwidgets. Default: False.
class deform.widget.FileUploadWidget(tmpstore, **kw)

Represent a file upload. Meant to work with a deform.FileData schema node.

This widget accepts a single required positional argument in its constructor: tmpstore. This argument should be passed an instance of an object that implements the deform.interfaces.FileUploadTempStore interface. Such an instance will hold on to file upload data during the validation process, so the user doesn’t need to reupload files if other parts of the form rendering fail validation. See also deform.interfaces.FileUploadTempStore.

Attributes/Arguments

template
The template name used to render the widget. Default: file_upload.
readonly_template
The template name used to render the widget in read-only mode. Default: readonly/file_upload.
size
The size attribute of the input field (default None).
class deform.widget.DateInputWidget(*args, **kwargs)

Renders a date picker widget.

The default rendering is as a native HTML5 date input widget, falling back to JQuery UI date picker widget (http://jqueryui.com/demos/datepicker/).

Most useful when the schema node is a colander.Date object.

Attributes/Arguments

size
The size, in columns, of the text input field. Defaults to None, meaning that the size is not included in the widget output (uses browser default size).
style
A string that will be placed literally in a style attribute on the text input tag. For example, ‘width:150px;’. Default: None, meaning no style attribute will be added to the input tag.
options
Options for configuring the widget (eg: date format)
template
The template name used to render the widget. Default: dateinput.
readonly_template
The template name used to render the widget in read-only mode. Default: readonly/textinput.
class deform.widget.DateTimeInputWidget(*args, **kwargs)

Renders a datetime picker widget.

The default rendering is as a native HTML5 datetime input widget, falling back to jQuery UI date picker with a JQuery Timepicker add-on (http://trentrichardson.com/examples/timepicker/).

Used for colander.DateTime schema nodes.

Attributes/Arguments

options
A dictionary of options that’s passed to the datetimepicker.
size
The size, in columns, of the text input field. Defaults to None, meaning that the size is not included in the widget output (uses browser default size).
style
A string that will be placed literally in a style attribute on the text input tag. For example, ‘width:150px;’. Default: None, meaning no style attribute will be added to the input tag.
template
The template name used to render the widget. Default: dateinput.
readonly_template
The template name used to render the widget in read-only mode. Default: readonly/textinput.
class deform.widget.DatePartsWidget(**kw)

Renders a set of <input type='text'/> controls based on the year, month, and day parts of the serialization of a colander.Date object or a string in the format YYYY-MM-DD. This widget is usually meant to be used as widget which renders a colander.Date type; validation likely won’t work as you expect if you use it against a colander.String object, but it is possible to use it with one if you use a proper validator.

Attributes/Arguments

template
The template name used to render the input widget. Default: dateparts.
readonly_template
The template name used to render the widget in read-only mode. Default: readonly/dateparts.
size
The size (in columns) of each date part input control. Default: None (let browser decide).
assume_y2k
If a year is provided in 2-digit form, assume it means 2000+year. Default: True.
class deform.widget.FormWidget(**kw)

The top-level widget; represents an entire form.

Attributes/Arguments

template
The template name used to render the widget. Default: form.
readonly_template
The template name used to render the widget in read-only mode. Default: readonly/form.
item_template
The template name used to render each item in the form. Default: mapping_item.
readonly_item_template
The template name used to render each item in the form. Default: readonly/mapping_item.
class deform.widget.TextAreaCSVWidget(**kw)

Widget used for a sequence of tuples of scalars; allows for editing CSV within a text area. Used with a schema node which is a sequence of tuples.

Attributes/Arguments

cols
The size, in columns, of the text input field. Defaults to None, meaning that the cols is not included in the widget output (uses browser default cols).
rows
The size, in rows, of the text input field. Defaults to None, meaning that the rows is not included in the widget output (uses browser default cols).
template
The template name used to render the widget. Default: textarea.
readonly_template
The template name used to render the widget in read-only mode. Default: readonly/textarea.
class deform.widget.TextInputCSVWidget(**kw)

Widget used for a tuple of scalars; allows for editing a single CSV line within a text input. Used with a schema node which is a tuple composed entirely of scalar values (integers, strings, etc).

Attributes/Arguments

template
The template name used to render the widget. Default: textinput.
readonly_template
The template name used to render the widget in read-only mode. Default: readonly/textinput.
size
The size, in columns, of the text input field. Defaults to None, meaning that the size is not included in the widget output (uses browser default size).
class deform.widget.ResourceRegistry(use_defaults=True)

A resource registry maps widget requirement name/version pairs to one or more relative resources. A resource registry can be passed to a deform.Form constructor; if a resource registry is not passed to the form constructor, a default resource registry is used by that form. The default resource registry contains only mappings from requirement names to resources required by the built-in Deform widgets (not by any add-on widgets).

If the use_defaults flag is True, the default set of Deform requirement-to-resource mappings is loaded into the registry. Otherwise, the registry is initialized without any mappings.

__call__(requirements)

Return a dictionary representing the resources required for a particular set of requirements (as returned by deform.Field.get_widget_requirements()). The dictionary will be a mapping from resource type (js and css are both keys in the dictionary) to a list of relative resource paths. Each path is relative to wherever you’ve mounted Deform’s static directory in your web server. You can use the paths for each resource type to inject CSS and Javascript on-demand into the head of dynamic pages that render Deform forms.

set_css_resources(requirement, version, *resources)

Set the CSS resources for the requirement/version pair, using resources as the set of relative resource paths.

set_js_resources(requirement, version, *resources)

Set the Javascript resources for the requirement/version pair, using resources as the set of relative resource paths.

deform.widget.default_resource_registry

The default resource registry (maps Deform-internal widget requirement strings to resource paths). This resource registry is used by forms which do not specify their own as a constructor argument, unless deform.Field.set_default_resource_registry() is used to change the default resource registry.

Table Of Contents

Previous topic

Internationalization

Next topic

Interfaces