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)
Choice fields are keyed on the json encoded representation of the value.
The value_mapper
argument can override this.
When rendered in HTML forms choice values must be converted to strings, and then back again when the form is submitted and processed.
The default strategy is to convert your choice keys to a JSON representation.
This handles the common cases of strings and integer keys well (and also
None
).
An alternative implementation is offered, which adds a key based on a simple indexing of the items based on their position in the list. For example, the choices:
[('11:00', 'Elevenses'), ('13:00', 'Lunch time'), ('16:00', 'Tea time')]
Would result in options indexed as follows:
<select>
<option value="0">Elevenses</option>
<option value="1">Lunch time</option>
<option value="2">Tea time</option>
</select>
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
The advantage with this strategy is that object identity is preserved. You can use any object as a value (perhaps a :class:datetime.time object in this case) and your form field will be populated with the very same object, thus elimating all the tedious mucking about converting values to strings and back again.
However while this sounds neat, in practice there are major disadvantages:
It’s fragile in the case that the list of values changes.
It’s hard to test — to create test values for a choice field you have to know the index of the value you want.
It’s hard to generate values for the field from other parts of your application (eg imagine a search form has a ‘category’ choice. Now you can’t easily generate search URLs with
category=...
in the querystring)
To enable this behaviour use the mapper
argument when creating the
widget:
from morf import fields, widgets
choicefield = fields.Choice(
choices=['a', 'b', 'c'],
widget=widgets.Select(mapper=widgets.IndexChoiceMapper())
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_value
converted 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
ob
to a raw input value
- validate(value)¶
Apply any required validation rules to
value
and raiseValidationError
if any condition is not met.
- widget¶
alias of
morf.widgets.Checkbox
- 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
ob
to a raw input value
- validate(value)¶
Apply any required validation rules to
value
and raiseValidationError
if any condition is not met.
- widget¶
alias of
morf.widgets.Select
- 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
morf.render.NullRenderer
- class morf.fields.Date(*args, **kwargs)¶
Date input field
- convert(s)¶
Return
input_value
converted to the required type, or raise a ValidationError
- class morf.fields.DateTime(*args, **kwargs)¶
Datetime input field
- convert(s)¶
Return
input_value
converted 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
ob
to 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=[], initial=[], processors=None, validators=None, widget=None, choices=None, maxlen=None, hidden=False, **kwargs)¶
A field for decimal number input
- convert(s)¶
Return
input_value
converted to the required type, or raise a ValidationError
- widget¶
alias of
morf.widgets.NumberInput
- class morf.fields.Field(name=None, displayname=None, label=None, empty_message=None, invalid_message=None, message=None, empty_values=None, default=[], initial=[], 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
- process_value(value)¶
Apply any processing to
value
and 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
value
and raiseValidationError
if any condition is not met.
- widget¶
alias of
morf.widgets.TextInput
- 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_value
converted 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
value
and 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
ob
to a raw input value
- render_with¶
alias of
morf.render.FieldRenderer
- validate(value)¶
Apply any required validation rules to
value
and raiseValidationError
if any condition is not met.
- widget¶
alias of
morf.widgets.TextInput
- class morf.fields.Hidden(name=None, displayname=None, label=None, empty_message=None, invalid_message=None, message=None, empty_values=None, default=[], initial=[], processors=None, validators=None, widget=None, choices=None, maxlen=None, hidden=False, **kwargs)¶
A hidden field
- render_with¶
alias of
morf.render.HiddenRenderer
- widget¶
alias of
morf.widgets.HiddenInput
- class morf.fields.Int(name=None, displayname=None, label=None, empty_message=None, invalid_message=None, message=None, empty_values=None, default=[], initial=[], processors=None, validators=None, widget=None, choices=None, maxlen=None, hidden=False, **kwargs)¶
A field for integer value input
- convert(s)¶
Return
input_value
converted to the required type, or raise a ValidationError
- widget¶
alias of
morf.widgets.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.
- 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
morf.render.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.
- validate(value)¶
Apply any required validation rules to
value
and raiseValidationError
if any condition is not met.
- widget¶
alias of
morf.widgets.CheckboxGroup
- class morf.fields.Object(name=None, displayname=None, label=None, empty_message=None, invalid_message=None, message=None, empty_values=None, default=[], initial=[], 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_value
converted to the required type, or raise a ValidationError
- rconvert(s)¶
Reverse convert
ob
to 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=[], initial=[], processors=None, validators=None, widget=None, choices=None, maxlen=None, hidden=False, **kwargs)¶
String field
- convert(s)¶
Return
input_value
converted to the required type, or raise a ValidationError
- class morf.fields.Time(*args, **kwargs)¶
Time input field
- convert(s)¶
Return
input_value
converted 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)
.