API Reference

zope.formlib.interfaces

Form interfaces

exception ConversionError(error_name, original_exception=None)[source]

Bases: exceptions.Exception

A conversion error occurred.

exception ErrorContainer[source]

Bases: exceptions.Exception

A base error class for collecting multiple errors.

exception FormError[source]

Bases: exceptions.Exception

There was an error in managing the form

interface IAction[source]

Extends: zope.formlib.interfaces.ISubPage

Form submit actions

available()

Return a boolean indicating whether the action is available

name

Action name

Implementation:zope.schema.TextLine
Read Only:False
Required:True
Default Value:None
Allowed Type:unicode
success(data)

Handle sucessful submition

This method is called when the action was submitted and the submitted data was valid.

submitted()

Return a boolean indicating whether the action was submitted

label

Action label

Implementation:zope.schema.TextLine
Read Only:False
Required:True
Default Value:None
Allowed Type:unicode
failure(data, errors)

Handle unsucessful submition

This method is called when the action was submitted and the submitted data was not valid.

validator

Action validator

This is a callable object that will be passed a form and an action and that returns a (possibly empty) list of widget input errors.

__name__

Action name with its prefix

Implementation:zope.schema.TextLine
Read Only:False
Required:True
Default Value:None
Allowed Type:unicode
validate(data)

Validate inputs

If an action was submitted and has a custom validator, then the validator result is returned. Otherwise, None is returned.

Validated inputs, if any, are placed into the mapping object passed as an argument,

data

Application data

Implementation:zope.schema.Dict
Read Only:False
Required:True
Default Value:None
Allowed Type:dict
condition

Action condition

This is a callable object that will be passed a form and an action and that returns a boolean to indicate whether the action is available.

__get__(form, form_class=None)

Bind an action to a form

Note that the other methods defined in this interface are valid only after the action has been bound to a form.

interface IActions[source]

An action collection

IActions provide ordered collections of actions that also support name-based lookup.

__iter__()

Return an interator in the actions, in order

__getitem__(name)

Get the action with the given name

Actions are computed from form fields (IFormField). If the form field used to create an action has a prefix, then that should be reflected in the name passed.

__add__(actions)

Add two actions collections

The result has the actions in the first collection followed by the actions in the second collection.

Actions should have different names in the two collections. The bahavior is undefined if the names overlap.

interface IAddFormCustomization[source]

Extends: zope.formlib.interfaces.IFormBaseCustomization

Form responsible for adding an object.

createAndAdd(data)

Create and return an object that has been added to the context.

The data argument is a dictionary with values supplied by the form.

If any user errors occur, they should be collected into a list and raised as a WidgetsError.

This is normally expected to simply call the create() and add() methods.

nextURL()

Return the URL to be displayed after the add operation.

This can be relative to the view’s context.

The default implementation returns self.context.nextURL(), i.e. it delegates to the IAdding view.

create(data)

Create and return an object to be added to the context.

The data argument is a dictionary with values supplied by the form.

If any user errors occur, they should be collected into a list and raised as a WidgetsError.

add(object)

Add an object to the context. Returns the added object.

interface IBoundAction[source]

Extends: zope.formlib.interfaces.IAction

An action that has been bound to a form

form

The form to which the action is bound

interface IBrowserWidget[source]

Extends: zope.formlib.interfaces.IWidget

A widget for use in a web browser UI.

__call__()

Render the widget.

hidden()

Render the widget as a hidden field.

error()

Render the validation error for the widget, or return an empty string if no error

interface IDisplayWidget[source]

Extends: zope.formlib.interfaces.IWidget

A widget for displaying a field value.

required

Required

If True, widget should be displayed as requiring input.

Display widgets should never be required.

Implementation:zope.schema.Bool
Read Only:False
Required:True
Default Value:None
Allowed Type:bool
interface IForm[source]

Base type for forms

This exists primarily to provide something for which to register form-related conponents.

interface IFormAPI[source]

API to facilitate creating forms, provided by zope.formlib.form

Action(label, **options)

Define a submit action

options:

condition
A callable or name of a method to call to test whether the action is applicable. if the value is a method name, then the method will be passed the action when called, otherwise, the callables will be passed the form and the action.
validator
A callable or name of a method to call to validate and collect inputs. This is called only if the action was submitted and if the action either has no condition, or the condition evaluates to a true value. If the validator is provided as a method name, the method will be called the action and a dictionary in which to save data. If the validator is provided as a callable, the callable will be called the form, the action, and a dictionary in which to save data. The validator normally returns a (usually empty) list of widget input errors. It may also return None to behave as if the action wasn’t submitted.
success
A handler, called when the the action was submitted and there are no validation errors. The handler may be provided as either a callable or a method name. If the handler is provided as a method name, the method will be called the action and a dictionary containing the form data. If the success handler is provided as a callable, the callable will be called the form, the action, and a dictionary containing the data. The handler may return a form result (e.g. page), or may return None to indicate that the form should generate it’s own output.
failure
A handler, called when the the action was submitted and there are validation errors. The handler may be provided as either a callable or a method name. If the handler is provided as a method name, the method will be called the action, a dictionary containing the form data, and a list of errors. If the failure handler is provided as a callable, the callable will be called the form, the action, a dictionary containing the data, and a list of errors. The handler may return a form result (e.g. page), or may return None to indicate that the form should generate it’s own output.
prefix
A form prefix for the action. When generating submit actions, the prefix should be combined with the action name, separating the two with a dot. The default prefix is “actions”form.
name
The action name, without a prefix. If the label is a valid Python identifier, then the lowe-case label will be used, otherwise, a hex encoding of the label will be used. If for some strange reason the labels in a set of actions with the same prefix is not unique, a name will have to be given for some actions to get unique names.
css_class
The CSS class for the action. The class defaults to “action”form.
data
A bag of extra information that can be used by handlers, validators, or conditions.
setUpEditWidgets(form_fields, form_prefix, context, request, adapters=None, for_display=False, ignore_request=False)

Set up widgets for editing or displaying content

An IWidgets is returned based on the give form fields.

The resulting widgets will be input widgets unless:

  • the corresponding form field was defined with the for_display option,
  • the underlying field is read only, or
  • the for_display opetion to setUpEditWidgets was passed a true value.

The widgets fields are bound to the context after it is adapted to the field schema. A mapping object can be passed to setUpEditWidgets to capture the adapters created. The adapters are placed in the mapping using both interfaces and interface names as keys.

If the ignore_request option is passed a true value, then widget’s rendered data will be set from the context, and user inputs will be ignored.

setUpInputWidgets(form_fields, form_prefix, context, request, ignore_request=False)

Set up widgets for input

An IWidgets is returned based on the give form fields.

All of the resulting widgets will be input widgets, regardless of whether the form fields are for display or whether the underlying schema fields are read only. This is so that one can easily build an input form, such as an add form from an existing schema.

The widgets will have prefixes that combine the given form prefix and any form-field prefixes.

A context argument is provided to allow field binding.

If ignore_request passed a true value, then the widgets will not initialize their values from the request.

Fields(*arguments, **options)

Create form-fields collection (IFormFields)

Creates a form-field collection from a collection of:

  • Schemas
  • Schema fields
  • form fields (IFormField)
  • form-field collections (IFormFields)

An IFormFields is returned.

The following options are supported:

name
Provide a name to use for the field.
prefix
The form-field prefix for new form-fields created. When form-field collections are passed, their contents keep their existing prefixes are retained.
for_display
A flag indicating whether the form-fiellds are to be used for display. This value is used for for_display attributes of all created form fields. This option does not effect input from form-field collections.
for_input
A flag indicating whether the form-fiellds are to be used for input. This value is used for for_input attributes of all created form fields. This option does not effect input from form-field collections.
render_context
A flag indicating whether the default values to render should come from the form context. See IFormField.
applyChanges(context, form_fields, data, adapters=None)

Apply form data to an object

For each form field that has data, the data are applied to the context argument. The context is adapter to the schema for each field. If an adapters mapping is passed, it will be used as a cache. Typically, it would be a mapping object populated when setUpEditWidgets was called.

Field(schema_field, **options)

Define a form field from a schema field and usage options

The following options are supported:

name
Provide a name to use for the field.
prefix
The form-field prefix.
for_display
A flag indicating whether the form-field is to be used for display. See IFormField.
for_input
A flag indicating whether the form-field is to be used for input. See IFormField.
custom_widget
Factory to use for widget construction. See IFormField.
render_context
A flag indicating whether the default value to render should come from the form context. See IFormField.
get_rendered
A callable or form method name to be used to get a default rendered value. See IFormField.
checkInvariants(form_fields, form_data)

Check schema invariants for input data

For each schema that was used to define the form fields and that had invariants relevent to the fields, the invariants are checked. Invariants that refer to fields not included in the form fields are ignored.

A list of errors is returned.

setUpDataWidgets(form_fields, form_prefix, context, request, data=(), for_display=False, ignore_request=False)

Set up widgets for input or display

An IWidgets is returned based on the give form fields.

The resulting widgets will be input widgets unless:

  • the corresponding form field was defined with the for_display option,
  • the underlying field is read only, or
  • the for_display opetion to setUpEditWidgets was passed a true value.

A data mapping argument can be passed to provide initial data.

If the ignore_request option is passed a true value, then widget’s rendered data will be set from the passed data or from field defaults, and user inputs will be ignored.

action(label, **options)

Create an action factory

This function creates a factory for creating an action from a function, using the function as the action success handler. The options are the same as for the Action constructor except that the options don’t include the success option.

The function is designed to be used as a decorator (Python 2.4 and later), as in:

@action("Edit")
def handle_edit(self, action, data):
    ...
validate(form, actions, form_prefix, data, default_validate=None)

Process a submitted action, if any

Check each of the given actions to see if any were submitted.

If an action was submitted, then validate the input. The input is called by calling the action’s validator, ir it has one, or by calling the default_validate passed in.

If the input is validated successfully, and the action has one success handler, then the success handler is called.

If the input was validated and there were errors, then the action’s failure handler will be called, if it has one.

If an action was submitted, then the function returns the result of validation and the action. The result of validation is normally a boolean, but may be None if no validator was provided.

If no action was submitted, then None is returned for both the result of validation and the action.

getWidgetsData(widgets, form_prefix, data)

Get input data and input errors

A sequence of input errors are returned. Any data available are added to the data argument, which must be a mapping argument. The keys in the output mapping are widget/form-field names without the form prefix.

FormBase

Base class for creating forms

The FormBase class provides reuasable implementation for creating forms. It implements ISubPage, IBrowserPage, and IFormBaseCustomization. Subclasses will override or use attributes defined by IFormBaseCustomization.

interface IFormBaseCustomization[source]

Extends: zope.formlib.interfaces.ISubPage, zope.publisher.interfaces.browser.IBrowserPage

Attributes provided by the Form base class

These attributes may be used or overridden.

Note that the update and render methods are designed to to work together. If you override one, you probably need to override the other, unless you use original versions in your override.

status

An update status message

This is normally generated by success or failure handlers.

setUpWidgets(ignore_request=False)

Set up the form’s widgets.

The default implementation uses the form definitions in the form_fields attribute and setUpInputWidgets.

The function should set the widgets attribute.

errors

Sequence of errors encountered during validation

template

Template used to display the form

This can be overridden in 2 ways:

  1. You can override the attribute in a subclass
  2. You can register an alternate named template, named “default” for your form.
form_fields

The form’s form field definitions

This attribute is used by many of the default methods.

resetForm()

Reset any cached data because underlying content may have changed

label

A label to display at the top of a form

form_reset

Boolean indicating whether the form needs to be reset

error_views()

Return views of any errors.

The errors are returned as an iterable.

widgets

The form’s widgets

  • set by setUpWidgets
  • used by validate
validate(action, data)

The default form validator

If an action is submitted and the action doesn’t have it’s own validator then this function will be called.

form_result

Return from action result method

interface IFormField[source]

Definition of a field to be included in a form

This should not be confused with a schema field.

for_display

Is the form field for display only?

If this attribute has a true value, then a display widget will be used for the field even if it is writable.

Implementation:zope.schema.Bool
Read Only:False
Required:True
Default Value:None
Allowed Type:bool
render_context

Should the rendered value come from the form context?

If this attribute has a true value, and there is no other source of rendered data, then use data from the form context to set the rendered value for the widget. This attribute is ignored if:

  • There is user input and user input is not being ignored, or
  • Data for the value is passed to setUpWidgets.

If the value is true, then it is evaluated as a collection of bit flags with the flags:

DISPLAY_UNWRITEABLE

If the field isn’t writable, then use a display widget

TODO untested

SKIP_UNAUTHORIZED

If the user is not priviledges to perform the requested operation, then omit a widget.

TODO unimplemented

Implementation:zope.schema.Choice
Read Only:False
Required:True
Default Value:False
for_input

Is the form field for input?

If this attribute has a true value, then an input widget will be used for the field even if it is readonly.

Implementation:zope.schema.Bool
Read Only:False
Required:True
Default Value:None
Allowed Type:bool
field

Schema field that defines the data of the form field

prefix

Prefix

Form-field prefix. The form-field prefix is used to disambiguate fields with the same name (e.g. from different schema) within a collection of form fields.

Implementation:zope.schema.ASCII
Read Only:False
Required:False
Default Value:‘’
Allowed Type:str
get_rendered

Object to call to get a rendered value

This attribute may be set to a callable object or to a form method name to call to get a value to be rendered in a widget.

This attribute is ignored if:

  • There is user input and user input is not being ignored, or
  • Data for the value is passed to setUpWidgets.
__name__

Field name

This is the name, without any proefix, used for the field. It is usually the same as the name of the for field’s schem field.

Implementation:zope.schema.ASCII
Read Only:False
Required:True
Default Value:None
Allowed Type:str
custom_widget

Factory to use for widget construction.

If not set, normal view lookup will be used.

interface IFormFields[source]

A colection of form fields (IFormField objects)

__getitem__(name)

Return the form field with the given name

If the desired firld has a prefix, then the given name should be the prefix, a dot, and the unprefixed name. Otherwise, the given name is just the field name.

Raise a KeyError if a field can’t be found for the given name.

get(name, default=None)

Return the form field with the given name

If the desired firld has a prefix, then the given name should be the prefix, a dot, and the unprefixed name. Otherwise, the given name is just the field name.

Return the default if a field can’t be found for the given name.

omit(*names)

Omit fields with given names

__iter__()

Iterate over the form fields

__len__()

Get the number of fields

__add__(form_fields)

Add two form fields collections (IFormFields)

Return a new IFormFields that is the concatination of the two IFormFields.

select(*names)

Select fields with given names in order

Return a new IFormFields that is a selection from the original IFormFields that has the named fields in the specified order.

interface IInputWidget[source]

Extends: zope.formlib.interfaces.IWidget

A widget for editing a field value.

applyChanges(content)

Validate the user input data and apply it to the content.

Return a boolean indicating whether a change was actually applied.

This raises an error if there is no user input.

required

Required

If True, widget should be displayed as requiring input.

By default, this value is the field’s ‘required’ attribute. This field can be set to False for widgets that always provide input (e.g. a checkbox) to avoid unnecessary ‘required’ UI notations.

Implementation:zope.schema.Bool
Read Only:False
Required:True
Default Value:None
Allowed Type:bool
hasInput()

Returns True if the widget has input.

Input is used by the widget to calculate an ‘input value’, which is a value that can be legally assigned to a field.

Note that the widget may return True, indicating it has input, but still be unable to return a value from getInputValue. Use hasValidInput to determine whether or not getInputValue will return a valid value.

A widget that does not have input should generally not be used to update its bound field. Values set using setRenderedValue() do not count as user input.

A widget that has been rendered into a form which has been submitted must report that it has input. If the form containing the widget has not been submitted, the widget shall report that it has no input.

getInputValue()

Return value suitable for the widget’s field.

The widget must return a value that can be legally assigned to its bound field or otherwise raise WidgetInputError.

The return value is not affected by setRenderedValue().

hasValidInput()

Returns True is the widget has valid input.

This method is similar to hasInput but it also confirms that the input provided by the user can be converted to a valid field value based on the field constraints.

interface IPageForm[source]

Extends: zope.formlib.interfaces.IForm, zope.publisher.interfaces.browser.IBrowserPage

A component that displays a form as a page.

interface ISimpleInputWidget[source]

Extends: zope.formlib.interfaces.IBrowserWidget, zope.formlib.interfaces.IInputWidget

A widget that uses a single HTML element to collect user input.

cssClass

CSS Class

The element class attribute.

Implementation:zope.schema.TextLine
Read Only:False
Required:False
Default Value:None
Allowed Type:unicode
tag

Tag

The widget HTML element.

Implementation:zope.schema.TextLine
Read Only:False
Required:True
Default Value:None
Allowed Type:unicode
type

Type

The element type attribute

Implementation:zope.schema.TextLine
Read Only:False
Required:False
Default Value:None
Allowed Type:unicode
extra

Extra

The element extra attribute.

Implementation:zope.schema.TextLine
Read Only:False
Required:False
Default Value:None
Allowed Type:unicode
interface ISourceQueryView[source]

View support for querying non-iterable sources

results(name)

Return the results of the query

The query view should use name as the prefix for its widgets.

The value returned is an iterable.

None may be returned to indicate that there are no results.

render(name)

Return a rendering of the search form elements

The query view should use name as the prefix for its widgets.

interface ISubPage[source]

A component that computes part of a page

prefix

Page-element prefix

All named or identified page elements in a subpage should have names and identifiers that begin with a subpage prefix followed by a dot.

Implementation:zope.schema.ASCII
Read Only:True
Required:True
Default Value:None
Allowed Type:str
update()

Update content ot view information based on user input

render()

Render the sub page, returning a unicode string

setPrefix(prefix)

Update the subpage prefix

interface ISubPageForm[source]

Extends: zope.formlib.interfaces.IForm, zope.formlib.interfaces.ISubPage

A component that displays a part of a page.

The rendered output must not have a form tag. It is the responsibility of the surrounding page to supply a form tag.

interface IWidget[source]

Extends: zope.browser.interfaces.IView

Generically describes the behavior of a widget.

Note that this level must be still presentation independent.

name

The unique widget name

This must be unique within a set of widgets.

hint

A hint regarding the use of the widget.

Hints are traditionally rendered using tooltips in GUIs, but may be rendered differently depending on the UI implementation.

Hint may be translated for the request.

The attribute may be implemented as either a read-write or read-only property, depending on the requirements for a specific implementation.

setRenderedValue(value)

Set the value to be rendered by the widget.

Calling this method will override any values provided by the user.

For input widgets (IInputWidget implementations), calling this sets the value that will be rendered even if there is already user input.

label

The widget label.

Label may be translated for the request.

The attribute may be implemented as either a read-write or read-only property, depending on the requirements for a specific implementation.

visible

A flag indicating whether or not the widget is visible.

setPrefix(prefix)

Set the name prefix used for the widget

The widget name is used to identify the widget’s data within input data. For example, for HTTP forms, the widget name is used for the form key.

It is acceptable to reset the prefix: set it once to read values from the request, and again to redraw with a different prefix but maintained state.

interface IWidgetFactory[source]

A factory that creates the widget

__call__(context, request)

Return a widget

interface IWidgetInputError[source]

Placeholder for a snippet View

doc()

Returns a string that represents the error message.

interface IWidgetInputErrorView[source]

Display an input error as a snippet of text.

snippet()

Convert a widget input error to an html snippet.

interface IWidgets[source]

A widget collection

IWidgets provide ordered collections of widgets that also support:

  • Name-based lookup
  • Keeping track of whether a widget is being used for input or display
__iter_input_and_widget__()

Return an iterator of flag/widget pairs

The flags indicate whether the corresponding widgets are used for input. This is necessary because there is currently no way to introspect a widget to determine whether it is being used for input.

__iter__()

Return an interator in the widgets, in order

__add__(widgets)

Add two widgets collections

The result has the widgets in the first collection followed by the widgets in the second collection.

Widgets should have different names in the two collections. The bahavior is undefined if the names overlap.

__getitem__(name)

Get the widget with the given name

Widgets are computed from form fields (IFormField). If the form field used to create a widget has a prefix, then that should be reflected in the name passed.

exception InvalidCSRFTokenError[source]

Bases: zope.formlib.interfaces.InvalidFormError

The form submit could not be handled as the CSRF token is missing or incorrect.

exception InvalidFormError[source]

Bases: exceptions.Exception

The form submit could not be validated.

exception MissingInputError(field_name, widget_title, errors=None)[source]

Bases: zope.formlib.interfaces.WidgetInputError

Required data was not supplied.

Initialize Error

errors is a ValidationError or a list of ValidationError objects

exception WidgetInputError(field_name, widget_title, errors=None)[source]

Bases: zope.exceptions.interfaces.UserError

One or more user input errors occurred.

Initialize Error

errors is a ValidationError or a list of ValidationError objects

exception WidgetsError(errors, widgetsData={})[source]

Bases: zope.formlib.interfaces.ErrorContainer

A collection of errors from widget processing.

widgetValues is a map containing the list of values that were obtained from the widgets, keyed by field name.

zope.formlib.boolwidgets

Browser widgets for items

class BooleanDisplayWidget(context, request)[source]

Bases: zope.formlib.widget.DisplayWidget

class CheckBoxWidget(context, request)[source]

Bases: zope.formlib.widget.SimpleInputWidget

A checkbox widget used to display Bool fields.

For more detailed documentation, including sample code, see tests/test_checkboxwidget.py.

hasInput()[source]

Check whether the field is represented in the form.

zope.formlib.errors

Error related things.

class InvalidCSRFTokenErrorView(context, request)[source]

Bases: zope.publisher.browser.BrowserPage

class InvalidErrorView(context, request)[source]

Bases: object

Display a validation error as a snippet of text.

snippet()[source]

Convert a widget input error to an html snippet

>>> from zope.interface.exceptions import Invalid
>>> error = Invalid("You made an error!")
>>> InvalidErrorView(error, None).snippet()
u'<span class="error">You made an error!</span>'

zope.formlib.exception

Form-related exception views

class WidgetInputErrorView(context, request)[source]

Bases: object

Display an input error as a snippet of text.

snippet()[source]

Convert a widget input error to an html snippet

>>> from zope.formlib.interfaces import WidgetInputError
>>> class TooSmallError(object):
...     def doc(self):
...         return "Foo input < 1"
>>> err = WidgetInputError("foo", "Foo", TooSmallError())
>>> view = WidgetInputErrorView(err, None)
>>> view.snippet()
u'<span class="error">Foo input &lt; 1</span>'

The only method that IWidgetInputError promises to implement is doc(). Therefore, other implementations of the interface should also work.

>>> from zope.formlib.interfaces import ConversionError
>>> err = ConversionError('Could not convert to float.')
>>> view = WidgetInputErrorView(err, None)
>>> view.snippet()
u'<span class="error">Could not convert to float.</span>'

zope.formlib.form

Forms.

This module provides the zope.formlib.interfaces.IFormAPI interface.

class Action(label, success=None, failure=None, condition=None, validator=None, prefix='actions', name=None, data=None)[source]

Bases: object

See zope.formlib.interfaces.IAction

bindMethods(**methods)[source]

Bind methods to the action

setName(name)[source]

Make sure name is ASCIIfiable. Use action label if name is None

setPrefix(prefix)[source]

Set prefix

AddForm

alias of zope.formlib.form.PageAddForm

class AddFormBase(context, request)[source]

Bases: zope.formlib.form.FormBase

DisplayForm

alias of zope.formlib.form.PageDisplayForm

class DisplayFormBase(context, request)[source]

Bases: zope.formlib.form.FormBase

EditForm

alias of zope.formlib.form.PageEditForm

class EditFormBase(context, request)[source]

Bases: zope.formlib.form.FormBase

Field

alias of zope.formlib.form.FormField

Fields

alias of zope.formlib.form.FormFields

Form

alias of zope.formlib.form.PageForm

class FormBase(context, request)[source]

Bases: zope.publisher.browser.BrowserPage

class FormField(field, name=None, prefix='', for_display=None, for_input=None, custom_widget=None, render_context=False, get_rendered=None, interface=None)[source]

Bases: object

Implementation of zope.formlib.interfaces.IFormField.

class FormFields(*args, **kw)[source]

Bases: object

Implementation of zope.formlib.interfaces.IFormFields.

omit(*names)[source]

Return a modified instance omitting given fields.

select(*names)[source]

Return a modified instance with an ordered subset of fields.

exception NoInputData[source]

Bases: zope.interface.exceptions.Invalid

There was no input data because:

  • It wasn’t asked for
  • It wasn’t entered by the user
  • It was entered by the user, but the value entered was invalid

This exception is part of the internal implementation of checkInvariants.

class PageAddForm(context, request)[source]

Bases: zope.formlib.form.AddFormBase

class PageDisplayForm(context, request)[source]

Bases: zope.formlib.form.DisplayFormBase

class PageEditForm(context, request)[source]

Bases: zope.formlib.form.EditFormBase

class PageForm(context, request)[source]

Bases: zope.formlib.form.FormBase

class SubPageDisplayForm(context, request)[source]

Bases: zope.formlib.form.DisplayFormBase

class SubPageEditForm(context, request)[source]

Bases: zope.formlib.form.EditFormBase

class SubPageForm(context, request)[source]

Bases: zope.formlib.form.FormBase

class Widgets(widgets, prefix_length=None, prefix=None)[source]

Bases: object

Implementation of zope.formlib.interfaces.IWidgets.

class action(label, actions=None, **options)[source]

Bases: object

See zope.formlib.interfaces.IFormAPI.action

applyChanges(context, form_fields, data, adapters=None)[source]

See zope.formlib.interfaces.IFormAPI.applyChanges

checkInvariants(form_fields, form_data, context)[source]

See zope.formlib.interfaces.IFormAPI.checkInvariants

expandPrefix(prefix)[source]

Expand prefix string by adding a trailing period if needed.

expandPrefix(p) should be used instead of p+’.’ in most contexts.

getWidgetsData(widgets, form_prefix, data)[source]

See zope.formlib.interfaces.IFormAPI.getWidgetsData

handleSubmit(actions, data, default_validate=None)[source]

Handle a submit.

setUpWidgets(form_fields, form_prefix=None, context=None, request=None, form=None, data=(), adapters=None, ignore_request=False)[source]

Sets up widgets.

zope.formlib.i18n

I18N support for zope.formlib

zope.formlib.itemswidgets

Browser widgets for items

class DropdownWidget(field, vocabulary, request)[source]

Bases: zope.formlib.itemswidgets.SelectWidget

Variation of the SelectWidget that uses a drop-down list.

Initialize the widget.

class ItemDisplayWidget(*args, **kw)[source]

Bases: zope.formlib.itemswidgets.SingleDataHelper, zope.formlib.itemswidgets.ItemsWidgetBase

Simple single-selection display that can be used in many cases.

class ItemsEditWidgetBase(field, vocabulary, request)[source]

Bases: zope.formlib.itemswidgets.SingleDataHelper, zope.formlib.itemswidgets.ItemsWidgetBase

Widget Base for rendering item-related fields.

These widgets work with Choice fields and Sequence fields that have Choice as value_type.

Initialize the widget.

renderItem(index, text, value, name, cssClass)[source]

Render an item for a particular value.

renderItemsWithValues(values)[source]

Render the list of possible values, with those found in values being marked as selected.

renderSelectedItem(index, text, value, name, cssClass)[source]

Render an item for a particular value that is selected.

setPrefix(prefix)[source]

Set the prefix of the input name.

Once we set the prefix of input field, we use the name of the input field and the postfix ‘-query’ for the associated query view.

class ItemsMultiDisplayWidget(*args, **kw)[source]

Bases: zope.formlib.itemswidgets.MultiDataHelper, zope.formlib.itemswidgets.ItemsWidgetBase

Displays a sequence of items.

renderItems(value)[source]

Render items of sequence.

class ItemsMultiEditWidgetBase(field, vocabulary, request)[source]

Bases: zope.formlib.itemswidgets.MultiDataHelper, zope.formlib.itemswidgets.ItemsEditWidgetBase

Items widget supporting multiple selections.

Initialize the widget.

class ItemsWidgetBase(field, vocabulary, request)[source]

Bases: zope.formlib.itemswidgets.TranslationHook, zope.formlib.widget.SimpleInputWidget

Convenience base class for widgets displaying items/choices.

Initialize the widget.

convertTokensToValues(tokens)[source]

Convert term tokens to the terms themselves.

Tokens are used in the HTML form to represent terms. This method takes the form tokens and converts them back to terms.

hasInput()[source]

Check whether we have any input.

setPrefix(prefix)[source]

Set the prefixes for the field names of the form.

textForValue(term)[source]

Extract a string from the term.

The term must be a vocabulary tokenized term.

This can be overridden to support more complex term objects. The token is returned here since it’s the only thing known to be a string, or str()able.

class ListDisplayWidget(*args, **kw)[source]

Bases: zope.formlib.itemswidgets.ItemsMultiDisplayWidget

Display widget for ordered multi-selection fields.

This can be used for both Sequence, List, and Tuple fields.

class MultiCheckBoxWidget(field, vocabulary, request)[source]

Bases: zope.formlib.itemswidgets.ItemsMultiEditWidgetBase

Provide a list of checkboxes that provide the choice for the list.

Initialize the widget.

renderItem(index, text, value, name, cssClass)[source]

Render an item of the list.

renderSelectedItem(index, text, value, name, cssClass)[source]

Render a selected item of the list.

class MultiDataHelper[source]

Bases: object

Mix-in helper class for getting the term from the HTML form.

This is used when we expect a multiple inputs, i.e. Sequence fields with a Choice field as value_type.

class MultiSelectFrozenSetWidget(field, vocabulary, request)[source]

Bases: zope.formlib.itemswidgets.MultiSelectWidget

Provide a selection list for the set to be selected.

Initialize the widget.

class MultiSelectSetWidget(field, vocabulary, request)[source]

Bases: zope.formlib.itemswidgets.MultiSelectWidget

Provide a selection list for the set to be selected.

Initialize the widget.

class MultiSelectWidget(field, vocabulary, request)[source]

Bases: zope.formlib.itemswidgets.ItemsMultiEditWidgetBase

Provide a selection list for the list to be selected.

Initialize the widget.

class OrderedMultiSelectWidget(field, vocabulary, request)[source]

Bases: zope.formlib.itemswidgets.ItemsMultiEditWidgetBase

A multi-selection widget with ordering support.

Initialize the widget.

choices()[source]

Return a set of tuples (text, value) that are available.

selected()[source]

Return a list of tuples (text, value) that are selected.

class RadioWidget(field, vocabulary, request)[source]

Bases: zope.formlib.itemswidgets.SelectWidget

Radio widget for single item choices.

This widget can be used when the number of selections is going to be small.

Initialize the widget.

renderItem(index, text, value, name, cssClass)[source]

Render an item of the list.

renderSelectedItem(index, text, value, name, cssClass)[source]

Render a selected item of the list.

class SelectWidget(field, vocabulary, request)[source]

Bases: zope.formlib.itemswidgets.ItemsEditWidgetBase

Provide a selection list for the item.

Initialize the widget.

class SetDisplayWidget(*args, **kw)[source]

Bases: zope.formlib.itemswidgets.ItemsMultiDisplayWidget

Display widget for unordered multi-selection fields.

This can be used for both Set field.

class SingleDataHelper[source]

Bases: object

Mix-in helper class for getting the term from the HTML form.

This is used when we expect a single input, i.e. the Choice field.

class TranslationHook[source]

Bases: object

A mixin class that provides the translation capabilities.

zope.formlib.namedtemplate

BBB

zope.formlib.objectwidget

Browser widgets for text-like data

class ObjectWidget(context, request, factory, **kw)[source]

Bases: zope.formlib.widget.BrowserWidget, zope.formlib.widget.InputWidget

A widget over an Interface that contains Fields.

factory

factory used to create content that this widget (field) represents

*_widget

Optional CustomWidgets used to generate widgets for the fields in this widget
applyChanges(content)[source]

See zope.formlib.interfaces.IInputWidget.applyChanges

getInputValue()[source]

Return converted and validated widget data.

The value for this field will be represented as an ObjectStorage instance which holds the subfield values as attributes. It will need to be converted by higher-level code into some more useful object (note that the default EditView calls applyChanges, which does this).

hasInput()[source]

Is there input data for the field

Return True if there is data and False otherwise.

hidden()[source]

Render the object as hidden fields.

setRenderedValue(value)[source]

Set the default data for the widget.

The given value should be used even if the user has entered data.

zope.formlib.sequencewidget

Browser widgets for sequences

class ListSequenceWidget(context, field, request, subwidget=None)[source]

Bases: zope.formlib.sequencewidget.SequenceWidget

class SequenceDisplayWidget(context, field, request, subwidget=None)[source]

Bases: zope.formlib.widget.DisplayWidget

class SequenceWidget(context, field, request, subwidget=None)[source]

Bases: zope.formlib.widget.BrowserWidget, zope.formlib.widget.InputWidget

A widget baseclass for a sequence of fields.

subwidget - Optional CustomWidget used to generate widgets for the
items in the sequence
getInputValue()[source]

Return converted and validated widget data.

If there is no user input and the field is required, then a MissingInputError will be raised.

If there is no user input and the field is not required, then the field default value will be returned.

A WidgetInputError is raised in the case of one or more errors encountered, inputting, converting, or validating the data.

hasInput()[source]

Is there input data for the field

Return True if there is data and False otherwise.

hidden()[source]

Render the list as hidden fields.

widgets()[source]

Return a list of widgets to display

class TupleSequenceWidget(context, field, request, subwidget=None)[source]

Bases: zope.formlib.sequencewidget.SequenceWidget

zope.formlib.source

Source widgets support

class IterableSourceVocabulary(source, request)[source]

Bases: object

Adapts an iterable source into a legacy vocabulary.

This can be used to wrap sources to make them usable with widgets that expect vocabularies. Note that there must be an ITerms implementation registered to obtain the terms.

class SourceDisplayWidget(field, source, request)[source]

Bases: zope.formlib.widget.DisplayWidget

class SourceDropdownWidget(field, source, request)[source]

Bases: zope.formlib.source.SourceSelectWidget

Variation of the SourceSelectWidget that uses a drop-down list.

class SourceInputWidget(field, source, request)[source]

Bases: zope.formlib.widget.InputWidget

class SourceListInputWidget(field, source, request)[source]

Bases: zope.formlib.source.SourceInputWidget

class SourceMultiCheckBoxWidget(field, source, request)[source]

Bases: zope.formlib.itemswidgets.MultiCheckBoxWidget

Provide a list of checkboxes that provide the choice for the list.

class SourceMultiSelectFrozenSetWidget(field, source, request)[source]

Bases: zope.formlib.itemswidgets.MultiSelectFrozenSetWidget

Provide a selection list for the frozenset to be selected.

class SourceMultiSelectSetWidget(field, source, request)[source]

Bases: zope.formlib.itemswidgets.MultiSelectSetWidget

Provide a selection list for the set to be selected.

class SourceMultiSelectWidget(field, source, request)[source]

Bases: zope.formlib.itemswidgets.MultiSelectWidget

A multi-selection widget with ordering support.

class SourceOrderedMultiSelectWidget(field, source, request)[source]

Bases: zope.formlib.itemswidgets.OrderedMultiSelectWidget

A multi-selection widget with ordering support.

class SourceRadioWidget(field, source, request)[source]

Bases: zope.formlib.itemswidgets.RadioWidget

Radio widget for single item choices.

class SourceSelectWidget(field, source, request)[source]

Bases: zope.formlib.itemswidgets.SelectWidget

Provide a selection list for the item.

class SourceSequenceDisplayWidget(field, source, request)[source]

Bases: zope.formlib.source.SourceDisplayWidget

zope.formlib.textwidgets

Browser widgets with text-based input

class ASCII(context, request)[source]

Bases: zope.formlib.textwidgets.Bytes

class ASCIIAreaWidget(context, request)[source]

Bases: zope.formlib.textwidgets.Bytes, zope.formlib.textwidgets.TextAreaWidget

ASCIIArea widget.

Multi-line string input.

>>> from zope.publisher.browser import TestRequest
>>> from zope.schema import ASCII
>>> field = ASCII(__name__='foo', title=u'on')
>>> request = TestRequest(form={'field.foo': u'Hello\r\nworld!'})
>>> widget = ASCIIAreaWidget(field, request)
>>> widget.hasInput()
True
>>> widget.getInputValue()
'Hello\nworld!'
class ASCIIDisplayWidget(context, request)[source]

Bases: zope.formlib.textwidgets.BytesDisplayWidget

ASCII display widget

class ASCIIWidget(*args)[source]

Bases: zope.formlib.textwidgets.BytesWidget

ASCII widget.

Single-line data (string) input

class Bytes(context, request)[source]

Bases: zope.formlib.widget.SimpleInputWidget

class BytesAreaWidget(context, request)[source]

Bases: zope.formlib.textwidgets.Bytes, zope.formlib.textwidgets.TextAreaWidget

BytesArea widget.

Multi-line string input.

>>> from zope.publisher.browser import TestRequest
>>> from zope.schema import Bytes
>>> field = Bytes(__name__='foo', title=u'on')
>>> request = TestRequest(form={'field.foo': u'Hello\r\nworld!'})
>>> widget = BytesAreaWidget(field, request)
>>> widget.hasInput()
True
>>> widget.getInputValue()
'Hello\nworld!'
class BytesDisplayWidget(context, request)[source]

Bases: zope.formlib.widget.DisplayWidget

Bytes display widget

class BytesWidget(*args)[source]

Bases: zope.formlib.textwidgets.Bytes, zope.formlib.textwidgets.TextWidget

Bytes widget.

Single-line data (string) input

>>> from zope.publisher.browser import TestRequest
>>> from zope.schema import BytesLine
>>> field = BytesLine(__name__='foo', title=u'on')
>>> request = TestRequest(form={'field.foo': u'Bob'})
>>> widget = BytesWidget(field, request)
>>> widget.hasInput()
True
>>> widget.getInputValue()
'Bob'
class DateDisplayWidget(context, request)[source]

Bases: zope.formlib.widget.DisplayWidget

Date display widget.

The cssClass and displayStyle attributes may be set to control the formatting of the value.

displayStyle must be one of ‘full’, ‘long’, ‘medium’, ‘short’, or None (’’ is accepted an an alternative to None to support provision of a value from ZCML).

class DateI18nWidget(*args)[source]

Bases: zope.formlib.textwidgets.TextWidget

I18n date entry widget.

The displayStyle attribute may be set to control the formatting of the value.

displayStyle must be one of ‘full’, ‘long’, ‘medium’, ‘short’, or None (’’ is accepted an an alternative to None to support provision of a value from ZCML).

class DateWidget(*args)[source]

Bases: zope.formlib.textwidgets.DatetimeWidget

Date entry widget.

class DatetimeDisplayWidget(context, request)[source]

Bases: zope.formlib.textwidgets.DateDisplayWidget

Datetime display widget.

The cssClass and displayStyle attributes may be set to control the formatting of the value.

displayStyle must be one of ‘full’, ‘long’, ‘medium’, ‘short’, or None (’’ is accepted an an alternative to None to support provision of a value from ZCML).

class DatetimeI18nWidget(*args)[source]

Bases: zope.formlib.textwidgets.DateI18nWidget

I18n datetime entry widget.

The displayStyle attribute may be set to control the formatting of the value.

displayStyle must be one of ‘full’, ‘long’, ‘medium’, ‘short’, or None (’’ is accepted an an alternative to None to support provision of a value from ZCML).

NOTE: If you need timezone information you need to set displayStyle to either ‘long’ or ‘full’ since other display styles just ignore it.

class DatetimeWidget(*args)[source]

Bases: zope.formlib.textwidgets.TextWidget

Datetime entry widget.

class DecimalWidget(*args)[source]

Bases: zope.formlib.textwidgets.TextWidget

class FileWidget(*args)[source]

Bases: zope.formlib.textwidgets.TextWidget

File Widget

hasInput()[source]

See IWidget.hasInput.

Returns True if the submitted request form contains a value for the widget, otherwise returns False.

Some browser widgets may need to implement a more sophisticated test for input. E.g. checkbox values are not supplied in submitted forms when their value is ‘off’ – in this case the widget will need to add a hidden element to signal its presence in the form.

class FloatWidget(*args)[source]

Bases: zope.formlib.textwidgets.TextWidget

class IntWidget(*args)[source]

Bases: zope.formlib.textwidgets.TextWidget

Integer number widget.

Let’s make sure that zeroes are rendered properly:

>>> from zope.schema import Int
>>> field = Int(__name__='foo', title=u'on')
>>> widget = IntWidget(field, None)
>>> widget.setRenderedValue(0)
>>> 'value="0"' in widget()
True
NativeString

alias of zope.formlib.textwidgets.Bytes

NativeStringDisplayWidget

alias of zope.formlib.textwidgets.BytesDisplayWidget

NativeStringWidget

alias of zope.formlib.textwidgets.BytesWidget

class PasswordWidget(*args)[source]

Bases: zope.formlib.textwidgets.TextWidget

Password Widget

class Text(context, request)[source]

Bases: zope.formlib.widget.SimpleInputWidget

class TextAreaWidget(context, request)[source]

Bases: zope.formlib.widget.SimpleInputWidget

TextArea widget.

Multi-line text (unicode) input.

>>> from zope.publisher.browser import TestRequest
>>> from zope.schema import Text
>>> field = Text(__name__='foo', title=u'on')
>>> request = TestRequest(form={'field.foo': u'Hello\r\nworld!'})
>>> widget = TextAreaWidget(field, request)
>>> widget.hasInput()
True
>>> widget.getInputValue()
u'Hello\nworld!'
>>> def normalize(s):
...   return '\n  '.join(filter(None, s.split(' ')))
>>> print(normalize( widget() ))
<textarea
  cols="60"
  id="field.foo"
  name="field.foo"
  rows="15"
  >Hello
world!</textarea>
>>> print(normalize( widget.hidden() ))
<input
  class="hiddenType"
  id="field.foo"
  name="field.foo"
  type="hidden"
  value="Hello&#13;&#10;world!"
  />

Calling setRenderedValue will change what gets output:

>>> widget.setRenderedValue("Hey\ndude!")
>>> print(normalize( widget() ))
<textarea
  cols="60"
  id="field.foo"
  name="field.foo"
  rows="15"
  >Hey
dude!</textarea>

Check that HTML is correctly encoded and decoded:

>>> request = TestRequest(
...     form={'field.foo': u'<h1>&copy;</h1>'})
>>> widget = TextAreaWidget(field, request)
>>> widget.getInputValue()
u'<h1>&copy;</h1>'
>>> print(normalize( widget() ))
<textarea
  cols="60"
  id="field.foo"
  name="field.foo"
  rows="15"
  >&lt;h1&gt;&amp;copy;&lt;/h1&gt;</textarea>

There was a but which caused the content of <textarea> tags not to be rendered correctly when there was a conversion error. Make sure the quoting works correctly:

>>> from zope.schema import Text
>>> field = Text(__name__='description', title=u'Description')
>>> from zope.formlib.interfaces import ConversionError
>>> class TestTextAreaWidget(TextAreaWidget):
...     def _toFieldValue(self, input):
...         if 'foo' in input:
...             raise ConversionError("I don't like foo.")
...         return input
...
>>> request = TestRequest(form={'field.description': u'<p>bar</p>'})
>>> widget = TestTextAreaWidget(field, request)
>>> widget.getInputValue()
u'<p>bar</p>'
>>> print(normalize( widget() ))
<textarea
  cols="60"
  id="field.description"
  name="field.description"
  rows="15"
  >&lt;p&gt;bar&lt;/p&gt;</textarea>
>>> request = TestRequest(form={'field.description': u'<p>foo</p>'})
>>> widget = TestTextAreaWidget(field, request)
>>> try:
...     widget.getInputValue()
... except ConversionError as error:
...     print(error.doc())
I don't like foo.
>>> print(normalize( widget() ))
<textarea
  cols="60"
  id="field.description"
  name="field.description"
  rows="15"
  >&lt;p&gt;foo&lt;/p&gt;</textarea>
class TextWidget(*args)[source]

Bases: zope.formlib.widget.SimpleInputWidget

Text widget.

Single-line text (unicode) input

>>> from zope.publisher.browser import TestRequest
>>> from zope.schema import TextLine
>>> field = TextLine(__name__='foo', title=u'on')
>>> request = TestRequest(form={'field.foo': u'Bob'})
>>> widget = TextWidget(field, request)
>>> widget.hasInput()
True
>>> widget.getInputValue()
u'Bob'
>>> def normalize(s):
...   return '\n  '.join(filter(None, s.split(' ')))
>>> print(normalize( widget() ))
<input
  class="textType"
  id="field.foo"
  name="field.foo"
  size="20"
  type="text"
  value="Bob"
  />
>>> print(normalize( widget.hidden() ))
<input
  class="hiddenType"
  id="field.foo"
  name="field.foo"
  type="hidden"
  value="Bob"
  />

Calling setRenderedValue will change what gets output:

>>> widget.setRenderedValue("Barry")
>>> print(normalize( widget() ))
<input
  class="textType"
  id="field.foo"
  name="field.foo"
  size="20"
  type="text"
  value="Barry"
  />

Check that HTML is correctly encoded and decoded:

>>> request = TestRequest(
...     form={'field.foo': u'<h1>&copy;</h1>'})
>>> widget = TextWidget(field, request)
>>> widget.getInputValue()
u'<h1>&copy;</h1>'
>>> print(normalize( widget() ))
<input
  class="textType"
  id="field.foo"
  name="field.foo"
  size="20"
  type="text"
  value="&lt;h1&gt;&amp;copy;&lt;/h1&gt;"
  />
class URIDisplayWidget(context, request)[source]

Bases: zope.formlib.widget.DisplayWidget

URI display widget.

Variables:linkTarget – The value of the target attribute for the generated hyperlink. If this is not set, no target attribute is generated.

zope.formlib.utility

Form utility functions

This is an implementation only used by zope.formlib.objectwidget, not by the rest of the widgets in zope.formlib. We would like to keep it this way.

This module is not directly tested: zope.app.form does have tests to test this, and the objectwidget implementation tests this indirectly.

At some point we would like to rewrite zope.formlib.objectwidget so it uses the infrastructure provided by zope.formlib itself.

applyWidgetsChanges(view, schema, target=None, names=None)[source]

Updates an object with values from a view’s widgets.

view contained the widgets that perform the update. By default, the widgets will update the view’s context.

target can be specified as an alternative object to update.

schema contrains the values provided by the widgets.

names can be specified to update a subset of the schema constrained values.

setUpWidget(view, name, field, viewType, value=<object object>, prefix=None, ignoreStickyValues=False, context=None)[source]

Sets up a single view widget.

The widget will be an attribute of the view. If there is already an attribute of the given name, it must be a widget and it will be initialized with the given value if not no_value.

If there isn’t already a view attribute of the given name, then a widget will be created and assigned to the attribute.

setUpWidgets(view, schema, viewType, prefix=None, ignoreStickyValues=False, initial={}, names=None, context=None)[source]

Sets up widgets for the fields defined by a schema.

Appropriate for collecting input without a current object implementing the schema (such as an add form).

view is the view that will be configured with widgets.

viewType is the type of widgets to create (e.g. IInputWidget or IDisplayWidget).

schema is an interface containing the fields that widgets will be created for.

prefix is a string that is prepended to the widget names in the generated HTML. This can be used to differentiate widgets for different schemas.

ignoreStickyValues is a flag that, when True, will cause widget sticky values to be replaced with the context field value or a value specified in initial.

initial is a mapping of field names to initial values.

names is an optional iterable that provides an ordered list of field names to use. If names is None, the list of fields will be defined by the schema.

context provides an alternative context for acquisition.

zope.formlib.widget

Browser Widget Definitions

class BrowserWidget(context, request)[source]

Bases: zope.formlib.widget.Widget, zope.publisher.browser.BrowserView

Base class for browser widgets.

>>> setUp()

The class provides some basic functionality common to all browser widgets.

Browser widgets have a required attribute, which indicates whether or not the underlying field requires input. By default, the widget’s required attribute is equal to the field’s required attribute:

>>> from zope.schema import Field
>>> from zope.publisher.browser import TestRequest
>>> field = Field(required=True)
>>> widget = BrowserWidget(field, TestRequest())
>>> widget.required
True
>>> field.required = False
>>> widget = BrowserWidget(field, TestRequest())
>>> widget.required
False

However, the two required values are independent of one another:

>>> field.required = True
>>> widget.required
False

Browser widgets have an error state, which can be rendered in a form using the error() method. The error method delegates the error rendering to a view that is registered as providing IWidgetInputErrorView. To illustrate, we can create and register a simple error display view:

>>> from zope.component import provideAdapter
>>> from zope.publisher.interfaces.browser import IDefaultBrowserLayer
>>> from zope.formlib.interfaces import IWidgetInputError
>>> @implementer(IWidgetInputErrorView)
... class SnippetErrorView:
...     def __init__(self, context, request):
...         self.context = context
...     def snippet(self):
...         return "The error: " + str(self.context.errors)
>>> provideAdapter(SnippetErrorView,
...                (IWidgetInputError, IDefaultBrowserLayer),
...                IWidgetInputErrorView, '')

Whever an error occurs, widgets should set _error:

>>> widget._error = WidgetInputError('foo', 'Foo', ('Err1', 'Err2'))

so that it can be displayed using the error() method:

>>> widget.error()
"The error: ('Err1', 'Err2')"
>>> tearDown()
class CustomWidgetFactory(widget_factory, *args, **kw)[source]

Bases: object

Custom Widget Factory.

class DisplayWidget(context, request)[source]

Bases: zope.formlib.widget.BrowserWidget

class InputWidget(context, request)[source]

Bases: zope.formlib.widget.Widget

Mixin class providing some default input widget methods.

class SimpleInputWidget(context, request)[source]

Bases: zope.formlib.widget.BrowserWidget, zope.formlib.widget.InputWidget

A baseclass for simple HTML form widgets.

>>> setUp()

Simple input widgets read input from a browser form. To illustrate, we will use a test request with two form values:

>>> from zope.publisher.browser import TestRequest
>>> request = TestRequest(form={
...     'field.foo': u'hello\r\nworld',
...     'baz.foo': u'bye world'})

Like all widgets, simple input widgets are a view to a field context:

>>> from zope.schema import Field
>>> field = Field(__name__='foo', title=u'Foo')
>>> widget = SimpleInputWidget(field, request)

Widgets are named using their field’s name:

>>> widget.name
'field.foo'

The default implementation for the widget label is to use the field title:

>>> widget.label
u'Foo'

According the request, the widget has input because ‘field.foo’ is present:

>>> widget.hasInput()
True
>>> widget.getInputValue()
u'hello\r\nworld'

Widgets maintain an error state, which is used to communicate invalid input or other errors:

>>> widget._error is None
True
>>> widget.error()
''

setRenderedValue is used to specify the value displayed by the widget to the user. This value, however, is not the same as the input value, which is read from the request:

>>> widget.setRenderedValue('Hey\nfolks')
>>> widget.getInputValue()
u'hello\r\nworld'
>>> widget._error is None
True
>>> widget.error()
''

You can use ‘setPrefix’ to remove or modify the prefix used to create the widget name as follows:

>>> widget.setPrefix('')
>>> widget.name
'foo'
>>> widget.setPrefix('baz')
>>> widget.name
'baz.foo'

getInputValue always returns a value that can legally be assigned to the widget field. To illustrate widget validation, we can add a constraint to its field:

>>> import re
>>> field.constraint = re.compile('.*hello.*').match

Because we modified the widget’s name, the widget will now read different form input:

>>> request.form[widget.name]
u'bye world'

This input violates the new field constraint and therefore causes an error when getInputValue is called:

>>> widget.getInputValue() #doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
WidgetInputError: ('foo', u'Foo', ConstraintNotSatisfied(u'bye world'))

Simple input widgets require that input be available in the form request. If input is not present, a MissingInputError is raised:

>>> del request.form[widget.name]
>>> widget.getInputValue() #doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
MissingInputError: ('baz.foo', u'Foo', None)

A MissingInputError indicates that input is missing from the form altogether. It does not indicate that the user failed to provide a value for a required field. The MissingInputError above was caused by the fact that the form does have any input for the widget:

>>> request.form[widget.name] #doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
KeyError: 'baz.foo'

If a user fails to provide input for a field, the form will contain the input provided by the user, namely an empty string:

>>> request.form[widget.name] = ''

In such a case, if the field is required, a WidgetInputError will be raised on a call to getInputValue:

>>> field.required = True
>>> widget.getInputValue() #doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
WidgetInputError: ('foo', u'Foo', RequiredMissing('foo'))

However, if the field is not required, the empty string will be converted by the widget into the field’s missing_value and read as a legal field value:

>>> field.required = False
>>> widget.getInputValue() is field.missing_value
True

Another type of exception is a conversion error. It is raised when a value cannot be converted to the desired Python object. Here is an example of a floating point.

>>> from zope.schema import Float
>>> field = Float(__name__='price', title=u'Price')
>>> from zope.formlib.interfaces import ConversionError
>>> class FloatWidget(SimpleInputWidget):
...     def _toFieldValue(self, input):
...         try:
...             return float(input)
...         except ValueError as v:
...             raise ConversionError('Invalid floating point data', v)
...
...     def _toFormValue(self, value):
...         value = super(FloatWidget, self)._toFormValue(value)
...         return '%.2f' % value
>>> request = TestRequest(form={'field.price': u'32.0'})
>>> widget = FloatWidget(field, request)
>>> widget.getInputValue()
32.0
>>> widget()
u'<input class="textType" id="field.price" name="field.price" required="True" type="text" value="32.00"  />'
>>> request = TestRequest(form={'field.price': u'<p>foo</p>'})
>>> widget = FloatWidget(field, request)
>>> try:
...     widget.getInputValue()
... except ConversionError as error:
...     print(error.doc())
Invalid floating point data
>>> widget()
u'<input class="textType" id="field.price" name="field.price" required="True" type="text" value="&lt;p&gt;foo&lt;/p&gt;"  />'
>>> tearDown()
hasInput()[source]

See IWidget.hasInput.

Returns True if the submitted request form contains a value for the widget, otherwise returns False.

Some browser widgets may need to implement a more sophisticated test for input. E.g. checkbox values are not supplied in submitted forms when their value is ‘off’ – in this case the widget will need to add a hidden element to signal its presence in the form.

class UnicodeDisplayWidget(context, request)[source]

Bases: zope.formlib.widget.DisplayWidget

Display widget that converts the value to unicode before display.

class Widget(context, request)[source]

Bases: object

Mixin class providing functionality common across widget types.

renderTag(tag, **kw)[source]

Render the tag. Well, not all of it, as we may want to / it.

zope.formlib.widgets

Browser widgets