formular.fields - Fields

This module provides the built-in fields.

Basic Fields

Fields representing basic types like strings, numbers etc.

class TextField(multiline=False, default=u'', **kwargs)

Bases: formular.fields.SizedField

Represents a field which holds text.

Parameters:
  • default – The default value for this field. If the given value contains a newline a Textarea is used as a widget.
  • multiline

    Forces the widget to be a Textarea.

    New in version 0.2.

Changed in version 0.2: Automatic change to Textarea if the default value contains a newline.

class PasswordField(multiline=False, default=u'', **kwargs)

Bases: formular.fields.TextField

Represents a field which holds a password.

widget
alias of PasswordInput
class NumberField(number_type=None, **kwargs)

Bases: formular.fields.ComparableField

Represents a field which holds a number of a given type.

Parameter:number_type – The constructor of the number type this field should hold. If the value is None the value number_type attribute of the class is used instead.
number_type
alias of int
class IntegerField
class FloatField
class DecimalField
Fields representing the number types built-in to python or available in the standard library. Use NumberField to represent any other type.
class BooleanField(name=None, label=None, default=missing, error_messages=None, **validators)

Bases: formular.fields.Field

Represents a field which holds a boolean value.

widget
alias of Checkbox
class SubmitField(label, **kwargs)

Represents a submit button.

New in version 0.2.

widget
alias of SubmitInput
class ChoiceField(choices=None, **kwargs)

Bases: formular.fields.Field

Represents a field which allows the user to choose between different values.

Parameter:choices

A list of values or a list of pairs. If a list of pairs is passed each pair should be a tuple of a value and a label which should be used instead of the value to be displayed to the user.

The choices can always be changed later using the choices attribute.

widget
alias of RadioButtonGroup
class MultiChoiceField(choices=None, **kwargs)

Bases: formular.fields.ChoiceField, formular.fields.SizedField

Represents a field which allows the user to make multiple choices between different values.

widget
alias of CheckboxGroup
class ReCAPTCHAField(label=u'Captcha', verify_server='http://api-verify.recaptcha.net/verify', api_server='http://api.recaptcha.net/', **kwargs)

Represents a reCAPTCHA.

Parameters:
  • verify_server – The URI to which the verification request is sent.
  • api_server – The server which provides the api for the captcha field.

Warning

Only one ReCAPTCHAField can be bound to a form.

New in version 0.2.

convert(value)
This method is not implemented.
value
True as long as the field is valid.
widget
alias of ReCAPTCHAWidget

Date and Time Fields

Note

These fields require Babel.

class TimeField(format='medium', **kwargs)

Bases: formular.fields.ComparableField

Represents a datetime.time instance.

Parameter:format – One of "full", "long" or "medium".
class DateField(format='short', **kwargs)

Bases: formular.fields.ComparableField

Represents a datetime.date instance.

Parameter:format“short”` or a custom date/time pattern.

Collection Fields

Fields representing collections/datastructures.

class Multiple(field, **kwargs)

Bases: formular.fields.SizedField

Represents multiple values of the same field.

>>> field = Multiple(IntegerField())
>>> field.validate([u"1", u"2", u"3"])
True
>>> field.value
[1, 2, 3]
widget
alias of MultipleWidget
class Seperated(field=None, seperator=u', ', strip_values=True, seperator_prefix=u' ', **kwargs)

Bases: formular.fields.Multiple

Represents multiple values seperated by a string.

Parameters:
  • seperator – The string the values are seperated with.
  • strip_values – If True each primitive value is stripped before converting it.
  • primitive_prefix

    A prefix which will be added to the seperator to create a primitive in to_primitive().

    This is useful in combination with strip_values:

    >>> f = Seperated(seperator=u",", strip_values=True,
                      seperator_prefix=u" ")
    >>> # a user can pass a primitive value like this for validation...
    >>> f.validate(u"foo, bar,baz")
    >>> # and the value is...
    >>> f.value
    [u"foo", u"bar", u"baz"]
    >>> # however the generated primitive looks like this...
    >>> f.to_primitive(f.value)
    u"foo, bar, baz"
    >>> # which looks a lot nicer then the primitive we got at
    >>> # validation
    
widget
alias of TextInput
class Mapping(mapped_fields, **kwargs)

Bases: formular.fields.Field

Represents multiple different fields:

>>> field = Mapping({"name": TextField(), "age": IntegerField()})
>>> field.validate({"name": u"John Doe", "age": u"42"})
Parameter:mapped_fields – A dictionary or a list of pairs, with names as keys and fields as their values.
widget
alias of MappingWidget

Making Your Own Field Type

Making your own field type is easy. You have to write a method which represents the value, the field represents as a string (to_primitive()) and a method which converts this string back to the value (convert()).

If the unicode representation is enough to convert it you don’t even have to implement to_primitive().

In addition to that you can define a default value for the type, if formular.datastructure.missing doesn’t fit, add the validators (validator_factories) and the error messages (error_messages).

However if there is already an abstract field implementing the behavior of the type you might not even have to add the validators and the error messages for those validators.

Abstract Fields

Fields implementing the validators and error messages for values with the specified behavior.

class SizedField(name=None, label=None, default=missing, error_messages=None, **validators)

Bases: formular.fields.Field

Represents a field, which value has a length.

Available validators for this field are:
class ComparableField(name=None, label=None, default=missing, error_messages=None, **validators)

Bases: formular.fields.Field

Represents a field with a comparable value.

Available validators for this field are:

The Field Base Class

class Field(name=None, label=None, default=missing, error_messages=None, **validators)

The base class of any field.

Parameters:
  • name – The name the field is should have. If you are assigning this field to a form, passing this name is unnecessary. Should the given name and the assigned differ, the assigned is used.
  • label – The name for the field which is shown to the user.
  • default – A default value.
  • error_messages – A dictionary which updates the error messages provided by the class.

Validators are passed as keyword arguments. The name of the validator is passed as key with the initial value as value.

Available validators for this field are:

Validators and error messages are inherited by subclasses.

as_widget(widget_type=None, dialect='html')

Returns a widget_type instance for this field. If no widget_type is given, widget is used instead.

Parameter:dialect – The dialect used to render this widget. Supported are "html" and "xhtml".
bind(form, name=None)
Binds the field to the form and assigns a name if given.
convert(value)

Converts the given value to unicode.

This method gets a unicode representation of the value this method should return. The given value should be a result of to_primitive() but it can be anything.

Therefore, if a conversion is not possible and the value is invalid, a ValueError may be raised. If that happens the “invalid” error message is added to errors.

copy(*args, **kwargs)

Returns a copy of the field, arguments passed to the constructor can be overridden by passing them.

Note

Copies are always unbound, even if the copied field is bound.

default
The default value for this field type. Default values may be mutable so so you should never modify them.
error_messages
Maps the validator names to the corresponding error messages.
is_valid
True if there are no errors.
classmethod register_as_validator(*args, **kwargs)

Decorator to add a validator.

Parameters:
  • name_or_callable – Either a name or a callable object with a __name__ attribute.
  • message

    The error message for this validator.

    New in version 0.2.

This method can be used like this:

@Field.register_as_validator
def required(form, is_required, value):
    return bool(value) if is_required else True

Or if you want to pass the message directly:

@Field.register_as_validator(message=u"This field is required")
...

However you might not want to have a required - or whatever the name is - function lying around somewhere, so you can just define the name explicitly:

@Field.register_as_validator("required")
def a_name_i_like_a_lot_more(form, is_required, value):
    return bool(value) if is_required else True

Of course you can also pass the message parameter here.

Note

If you register a validator on a field class, this validator will be registered on every subclass of this field. The same goes for error messages

reset()
Resets the field after validation.
to_primitive(value)

Converts the given value to unicode.

A subclass may want to override this method if the unicode representation of value is not sufficient enough to get the value back.

However this method has to return a unicode string and must not fail.

unbind(with_name=False)
Unbinds the field from the form and the name if with_name is True.
validate(value, convert=True)

Converts and validates value. If the validation fails with one or more errors this method returns False otherwise True.

Parameters:
  • value – A primitive or converted value.
  • convert

    If the given value is already converted this has to be set to False.

    New in version 0.2.

The parsed value can be accessed through the value attribute, the errors are stored as a formular.exceptions.ValidationError through the errors attribute.

validator_factories
A dictionary of validators used by this field. Keys are the names which should be used as keyword arguments in the constructor. Values are validator factories as returned by formular.validators.as_validator().
value
The parsed value or the default value.
widget
The widget type used to render this field.

Table Of Contents

Previous topic

Writing Extensions

Next topic

formular.forms - Forms

This Page