Fields reference¶
Single value input fields¶
Morf includes many single value input fields:
Str,
Int,
Decimal,
Time,
Date,
Datetime,
and
Bool.
These all take a single input value from the user
and convert it to the destination type.
Date and time fields¶
Specify the date format using the format argument:
starts_at = fields.Date(format='%d/%m/%Y')
opening_time = fields.Time(format='%H:%M')
next_reminder = fields.DateTime(format='%Y-%m-%d %H:%M:%S')
If a user supplied date can’t be parsed using the given format,
these fields fall back on
python-dateutil <https://pypi.python.org/pypi/python-dateutil>
to parse the input. If you expect European style dates to be given you will
probably want to specify dayfirst=True:
starts_at = fields.Date(format='%d/%m/%Y', dayfirst=True)
Special field types¶
fields.Constant¶
Not modifiable by the user, a Constant
field passes a known value through to
the submitted data dict:
class MorfConBookingForm(BookingForm):
event_name = fields.Constant('MorfCon 2014')
fields.ListOf¶
morf.fields.ListOf fields represent a list of other fields.
These can be any field type (this includes instances of
morf.form.Form, which can act as fields).
When rendered, a ListOf field will show one control per
item in the bound input, plus optional spare empty fields for the user to add
more items to the collection. Set spare, min and max when constructing a
ListOf field to control this, eg:
team_members = fields.ListOf(PlayerForm(), label='Players',
min=4, spare=4, max=11)
Choice fields¶
Choice fields represent a choice from a fixed list of possiblities
Choice fields need to be passed a list of choices. This can be a list, a callable returning a list or the name of a method on the form that returns a list:
def get_countries():
return [('gb', 'United Kingdom'),
('fr', 'France'),
('de', 'Germany')]
class MyForm(HTMLForm):
title = fields.Choice(choices=['Mr', 'Mrs', 'Miss'])
country = fields.Choice(choices=get_countries)
year = fields.Choice(choices='year_choices')
def year_choices(self):
current_year = date.today().year
return range(current_year, current_year - 100, -1)
The list of choices should be in one of the following formats:
A list of items to be used both as values and labels, eg
['red', 'green', 'blue']A list of (value, label) pairs, eg
[('#ff0000', 'Red'), ('#00ff00', 'Green'), ('#0000ff', 'Blue')]
The list may also contain one or more OptGroup.
In an HTML select widget these would be rendered using the <optgroup>
element:
even_numbers = [(2, 'Two'), (4, 'Four'), (6, 'Six')]
odd_numbers = [(1, 'One'), (3, 'Three'), (5, 'Five')]
number_choices = [('Even numbers', OptGroup(even_numbers)),
('Odd numbers', OptGroup(odd_numbers))]
Choice fields require that the input value is a valid selection from the
list of choices. Set validate_choices=False to disable this:
donation_amount = fields.Choice(choices=[(10, '10€'), (20, '20€')],
validate_choices=False)
Mapping choice values to strings¶
When rendered in HTML forms choice values must be converted to strings, and then back again when the form is submitted and processed.
Starting from version 2.0, morf.fields.Choice fields with non-string
values will have their values converted to strings when rendered in HTML.
Two other options exist.
JSONChoiceMapper converts choice values to JSON when rendering as HTML. This was the default behaviour prior to v2.0.
IndexChoiceMapper uses the position of each value in the choice list as the key. For example, the choices:
Would result in options indexed as follows:
When a user selects for example value 2 (Tea time),
morf looks up the index and populates the field with the
original object, in this case 16:00
To enable this behaviour use the mapper argument when creating the
widget:
To revert to the pre-2.0 default of using the
JSONChoiceMapper globally, add this code to your
application:
fields.MultipleChoice¶
A variant of the normal choice field, MultipleChoice
fields allow the user to select more than one choice. By default
MultipleChoice fields are rendered using the
morf.widgets.CheckboxGroup widget.
Fields API reference¶
- class morf.fields.Bool(*args, **kwargs)¶
- convert(s)¶
Return
input_valueconverted to the required type, or raise a ValidationError
- is_considered_empty(value)¶
Return true if the given value is considered empty, triggering the field’s default value to be used instead.
- rconvert(ob)¶
Reverse convert
obto a raw input value
- validate(value)¶
Apply any required validation rules to
valueand raiseValidationErrorif any condition is not met.
- class morf.fields.Choice(*args, **kwargs)¶
A field representing a single choice from a fixed list
- is_considered_empty(value)¶
Return true if the given value is considered empty, triggering the field’s default value to be used instead.
- rconvert(value)¶
Reverse convert
obto a raw input value
- validate(value)¶
Apply any required validation rules to
valueand raiseValidationErrorif any condition is not met.
- class morf.fields.Constant(value, *args, **kwargs)¶
- bind_input(raw, validate=True, _internal=False)¶
Bind the raw submitted value to the field
Field.extract_raw can be used to extract the raw value in the correct format for this method.
- is_considered_empty(value)¶
Return true if the given value is considered empty, triggering the field’s default value to be used instead.
- render_with¶
alias of
NullRenderer
- class morf.fields.Date(*args, **kwargs)¶
Date input field
- convert(s)¶
Return
input_valueconverted to the required type, or raise a ValidationError
- format = '%Y-%m-%d'¶
Default format for displaying the date
- class morf.fields.DateTime(*args, **kwargs)¶
Datetime input field
- convert(s)¶
Return
input_valueconverted to the required type, or raise a ValidationError
- format = '%Y-%m-%d %H:%M:%S'¶
Default format for displaying the date
- rconvert(ob)¶
Reverse convert
obto a raw input value
- class morf.fields.Decimal(name=None, displayname=None, label=None, empty_message=None, invalid_message=None, message=None, empty_values=None, default=<object object>, initial=<object object>, processors=None, validators=None, widget=None, choices=None, maxlen=None, hidden=False, **kwargs)¶
A field for decimal number input
- convert(s)¶
Return
input_valueconverted to the required type, or raise a ValidationError
- widget¶
alias of
NumberInput
- class morf.fields.Field(name=None, displayname=None, label=None, empty_message=None, invalid_message=None, message=None, empty_values=None, default=<object object>, initial=<object object>, processors=None, validators=None, widget=None, choices=None, maxlen=None, hidden=False, **kwargs)¶
Base class for all field types (except
morf.form.Form, which is a special case).- choice_values(_choices=None)¶
Return a flattened list of all values present in the choices property
- property choices¶
- process_value(value)¶
Apply any processing to
valueand return the new value.Processing might include operations such as trimming whitespace from strings, and happens after type conversion but before validation.
- validate(value)¶
Apply any required validation rules to
valueand raiseValidationErrorif any condition is not met.
- class morf.fields.FieldBase¶
The base field class.
As well as regular fields (see
Field), this is also the base formorf.form.Form- DICT = 'scalar'¶
A field representing a mapping of multiple values, eg an entire form
- LIST = 'list'¶
A field representing an ordered set of values, each of which may be of any type
- SCALAR = 'scalar'¶
A field representing a single dimensioned value, eg a string or number
- SIMPLE_LIST = 'simplelist'¶
A field representing an ordered set of values, each of which must be a scalar type
- bind_input(raw, validate=True, _internal=False)¶
Bind the raw submitted value to the field
Field.extract_raw can be used to extract the raw value in the correct format for this method.
- choices = None¶
Valid choices, typically used for a select or radio group field
- convert(input_value)¶
Return
input_valueconverted to the required type, or raise a ValidationError
- dimensionality = 'scalar'¶
Does the field encode a single scalar value, a mapping or a list? Used by RequestBindAdapter to generate appropriate fieldnames
- displayname = None¶
The display name for the field. Example: ‘email address’
- extract_raw(raw)¶
Process the raw value given to us by the form. For compound fields this could be a list or dict (eg a date separated into
{'d': ..., 'm': ..., 'y': ...}components) which need to be processed into a single value.
- property fieldname¶
The name of the field. Used as the html name attribute when rendering form controls. Example:
'email'
- is_considered_empty(value)¶
Return true if the given value is considered empty, triggering the field’s default value to be used instead.
- label = None¶
The label to display next to the field. Example: ‘Please enter your email address’
- process(value)¶
A convenience method for binding a raw value and returning the processed value (or raising a ValidationError)
- process_value(value)¶
Apply any processing to
valueand return the new value.Processing might include operations such as trimming whitespace from strings, and happens after type conversion but before validation.
- rconvert(ob)¶
Reverse convert
obto a raw input value
- render_with¶
The default class to use to render the field (label, errors, control)
alias of
FieldRenderer
- validate(value)¶
Apply any required validation rules to
valueand raiseValidationErrorif any condition is not met.
- class morf.fields.Hidden(name=None, displayname=None, label=None, empty_message=None, invalid_message=None, message=None, empty_values=None, default=<object object>, initial=<object object>, processors=None, validators=None, widget=None, choices=None, maxlen=None, hidden=False, **kwargs)¶
A hidden field
- render_with¶
alias of
HiddenRenderer
- widget¶
alias of
HiddenInput
- class morf.fields.Int(name=None, displayname=None, label=None, empty_message=None, invalid_message=None, message=None, empty_values=None, default=<object object>, initial=<object object>, processors=None, validators=None, widget=None, choices=None, maxlen=None, hidden=False, **kwargs)¶
A field for integer value input
- convert(s)¶
Return
input_valueconverted to the required type, or raise a ValidationError
- widget¶
alias of
NumberInput
- class morf.fields.ListOf(field, *args, **kwargs)¶
A field holding a list of other fields
- bind_input(raw, validate=True, _internal=False)¶
Bind the raw submitted value to the field
Field.extract_raw can be used to extract the raw value in the correct format for this method.
- dimensionality = 'list'¶
Does the field encode a single scalar value, a mapping or a list? Used by RequestBindAdapter to generate appropriate fieldnames
- is_considered_empty(value)¶
Lists might conceivably be populated by a list or an iterable. Calling ‘if [] in self.empty_values’ gives us an error ([] isn’t hashable), so to retain flexibility we just check bool(value), which will catch empty lists, tuples, Undefined and None.
- render_with¶
alias of
ListRenderer
- class morf.fields.MultipleChoice(*args, **kwargs)¶
A field representing a set of choices from a fixed list
- bind_input(raw, validate=True, _internal=False)¶
Bind the raw submitted value to the field
Field.extract_raw can be used to extract the raw value in the correct format for this method.
- dimensionality = 'simplelist'¶
Does the field encode a single scalar value, a mapping or a list? Used by RequestBindAdapter to generate appropriate fieldnames
- validate(value)¶
Apply any required validation rules to
valueand raiseValidationErrorif any condition is not met.
- widget¶
alias of
CheckboxGroup
- class morf.fields.Object(name=None, displayname=None, label=None, empty_message=None, invalid_message=None, message=None, empty_values=None, default=<object object>, initial=<object object>, processors=None, validators=None, widget=None, choices=None, maxlen=None, hidden=False, **kwargs)¶
A field type that attempts no type conversion of the value passed, treating it as an opaque object.
- convert(s)¶
Return
input_valueconverted to the required type, or raise a ValidationError
- rconvert(s)¶
Reverse convert
obto a raw input value
- class morf.fields.Str(name=None, displayname=None, label=None, empty_message=None, invalid_message=None, message=None, empty_values=None, default=<object object>, initial=<object object>, processors=None, validators=None, widget=None, choices=None, maxlen=None, hidden=False, **kwargs)¶
String field
- convert(s)¶
Return
input_valueconverted to the required type, or raise a ValidationError
- class morf.fields.Time(*args, **kwargs)¶
Time input field
- convert(s)¶
Return
input_valueconverted to the required type, or raise a ValidationError
- format = '%H:%M:%S'¶
Default format for displaying the time
- morf.fields.make_displayname(s)¶
Convert a field name to an appropriate label, eg from
'a_field'to'A field'
Choices API reference¶
- class morf.choices.OptGroup(choices)¶
Mark an optgroup nested in a list of choices
- morf.choices.expand_choices(choices)¶
Return an iterator over the available choices. The iterator will always yield tuples of
(value, label).