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.
- 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 別のテンプレートシステムを使う. 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 (高レベル) deform.Field.get_widget_resources() メソッド).
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.
Return the subfield of this field named name or raise a KeyError if a subfield does not exist named name.
Iterate over the children fields of this field.
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 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 the pstruct into a cstruct and return the cstruct.
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.
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.
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.
Return the msg attribute of the error attached to this field. If the error attribute is None, the return value will be None.
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 (低レベル) deform.Field.get_widget_requirements() メソッド.
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.
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 the template named template using kw as the top-level keyword arguments (augmented with field and cstruct if necessary)
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 the cstruct of this node (and its child nodes) using appstruct as input.
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.
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 the cstruct of this node (and its child nodes) using pstruct as input.
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 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.
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(...)).
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.
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.
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.
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 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:
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 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
Field representing an entire form.
Arguments:
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).
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:
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:
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: ウィジェットの要求を指定する and ウィジェットの要求 (requirement) とリソース.
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.
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.
The handle_error method of a widget must:
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.
Renders an <input type="text"/> widget.
Attributes/Arguments
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 テキスト入力マスクの使用.
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
A dictionary or sequence of two-tuples containing jquery-maskMoney options. The valid options are:
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 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
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.
Renders an <input type="hidden"/> widget.
Attributes/Arguments
Renders a <textarea> widget.
Attributes/Arguments
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
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 passed to TinyMCE. Customise by using options.
Options to pass to TinyMCE that will override default_options.
Renders an <input type="checkbox"/> widget.
Attributes/Arguments
Renders two text input fields: ‘value’ and ‘confirm’. Validates that the ‘value’ value matches the ‘confirm’ value.
Attributes/Arguments
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 テキスト入力マスクの使用.
Renders two password input fields: ‘password’ and ‘confirm’. Validates that the ‘password’ value matches the ‘confirm’ value.
Attributes/Arguments
Renders a sequence of <input type="check"/> buttons based on a predefined set of values.
Attributes/Arguments
Used in the values argument passed to an instance of SelectWidget to render an <optgroup> HTML tag.
Attributes/Arguments
Renders <select> field based on a predefined set of values.
Attributes/Arguments
A sequence of items where each item must be either:
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).
Renders a sequence of <input type="radio"/> buttons based on a predefined set of values.
Attributes/Arguments
Renders a mapping into a set of fields.
Attributes/Arguments
Renders a sequence (0 .. N widgets, each the same as the other) into a set of fields.
Attributes/Arguments
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:
Default: Add ${subitem_title}.
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
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
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
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
The top-level widget; represents an entire form.
Attributes/Arguments
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
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
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.
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 the CSS resources for the requirement/version pair, using resources as the set of relative resource paths.
Set the Javascript resources for the requirement/version pair, using resources as the set of relative resource paths.
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.