Horizon Forms

Horizon ships with some very useful base form classes, form fields, class-based views, and javascript helpers which streamline most of the common tasks related to form handling.

Form Classes

class horizon.forms.base.DateForm(*args, **kwargs)[source]

A simple form for selecting a range of time.

property media

Return all media required to render the widgets on this form.

class horizon.forms.base.SelfHandlingForm(request, *args, **kwargs)[source]

A base Form class which includes processing logic in its subclasses.

api_error(message)[source]

Adds an error to the form’s error dictionary.

It can be used after validation based on problems reported via the API. This is useful when you wish for API errors to appear as errors on the form rather than using the messages framework.

property media

Return all media required to render the widgets on this form.

set_warning(message)[source]

Sets a warning on the form.

Unlike NON_FIELD_ERRORS, this doesn’t fail form validation.

Form Fields

class horizon.forms.fields.ChoiceInput(name, value, attrs, choice, index)[source]

ChoiceInput class from django 1.10.7 codebase

An object used by ChoiceFieldRenderer that represents a single <input type=’$input_type’>.

class horizon.forms.fields.DynamicChoiceField(add_item_link=None, add_item_link_args=None, *args, **kwargs)[source]

ChoiceField that make dynamically updating its elements easier.

Notably, the field declaration takes an extra argument, add_item_link which may be a string or callable defining the URL that should be used for the “add” link associated with the field.

widget

alias of DynamicSelectWidget

class horizon.forms.fields.DynamicSelectWidget(attrs=None, choices=(), data_attrs=(), transform=None, transform_html_attrs=None)[source]

Select widget to handle dynamic changes to the available choices.

A subclass of the Select widget which renders extra attributes for use in callbacks to handle dynamic changes to the available choices.

render(*args, **kwargs)[source]

Render the widget as an HTML string.

class horizon.forms.fields.DynamicTypedChoiceField(add_item_link=None, add_item_link_args=None, *args, **kwargs)[source]

Simple mix of DynamicChoiceField and TypedChoiceField.

class horizon.forms.fields.ExternalFileField(*args, **kwargs)[source]

Special FileField to upload file to some external location.

This is a special flavor of FileField which is meant to be used in cases when instead of uploading file to Django it should be uploaded to some external location, while the form validation is done as usual. It should be paired with ExternalUploadMeta metaclass embedded into the Form class.

class horizon.forms.fields.ExternalUploadMeta(name, bases, attrs)[source]

Metaclass to process ExternalFileField fields in a specific way.

Set this class as the metaclass of a form that contains ExternalFileField in order to process ExternalFileField fields in a specific way. A hidden CharField twin of FieldField is created which contains just the filename (if any file was selected on browser side) and a special clean method for FileField is defined which extracts just file name. This allows to avoid actual file upload to Django server, yet process form clean() phase as usual. Actual file upload happens entirely on client-side.

class horizon.forms.fields.IPField(*args, **kwargs)[source]

Form field for entering IP/range values, with validation.

Supports IPv4/IPv6 in the format: .. xxx.xxx.xxx.xxx .. xxx.xxx.xxx.xxx/zz .. ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff .. ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff/zz and all compressed forms. Also the short forms are supported: xxx/yy xxx.xxx/yy

version

Specifies which IP version to validate, valid values are 1 (fields.IPv4), 2 (fields.IPv6) or both - 3 (fields.IPv4 | fields.IPv6). Defaults to IPv4 (1)

mask

Boolean flag to validate subnet masks along with IP address. E.g: 10.0.0.1/32

mask_range_from
Subnet range limitation, e.g. 16
That means the input mask will be checked to be in the range
16:max_value. Useful to limit the subnet ranges
to A/B/C-class networks.
clean(value)[source]

Validate the given value and return its “cleaned” value as an appropriate Python object. Raise ValidationError for any errors.

class horizon.forms.fields.MACAddressField(*, required=True, widget=None, label=None, initial=None, help_text='', error_messages=None, show_hidden_initial=False, validators=(), localize=False, disabled=False, label_suffix=None)[source]

Form field for entering a MAC address with validation.

Supports all formats known by netaddr.EUI(), for example: .. xx:xx:xx:xx:xx:xx .. xx-xx-xx-xx-xx-xx .. xxxx.xxxx.xxxx

clean(value)[source]

Validate the given value and return its “cleaned” value as an appropriate Python object. Raise ValidationError for any errors.

class horizon.forms.fields.MultiIPField(*args, **kwargs)[source]

Extends IPField to allow comma-separated lists of addresses.

clean(value)[source]

Validate the given value and return its “cleaned” value as an appropriate Python object. Raise ValidationError for any errors.

class horizon.forms.fields.SelectWidget(attrs=None, choices=(), data_attrs=(), transform=None, transform_html_attrs=None)[source]

Custom select widget.

It allows to render data-xxx attributes from choices. This widget also allows user to specify additional html attributes for choices.

data_attrs

Specifies object properties to serialize as data-xxx attribute. If passed (‘id’, ), this will be rendered as: <option data-id=”123”>option_value</option> where 123 is the value of choice_value.id

transform

A callable used to render the display value from the option object.

transform_html_attrs

A callable used to render additional HTML attributes for the option object. It returns a dictionary containing the html attributes and their values. For example, to define a title attribute for the choices:

helpText = { 'Apple': 'This is a fruit',
          'Carrot': 'This is a vegetable' }

def get_title(data):
    text = helpText.get(data, None)
    if text:
        return {'title': text}
    else:
        return {}

....
....

widget=forms.ThemableSelect( attrs={'class': 'switchable',
                                 'data-slug': 'source'},
                        transform_html_attrs=get_title )

self.fields[<field name>].choices =
    ([
        ('apple','Apple'),
        ('carrot','Carrot')
    ])
build_attrs(extra_attrs=None, **kwargs)[source]

Helper function for building an attribute dictionary.

render(name, value, attrs=None, renderer=None)[source]

Render the widget as an HTML string.

class horizon.forms.fields.SubWidget(parent_widget, name, value, attrs, choices)[source]

SubWidget class from django 1.10.7 codebase

Some widgets are made of multiple HTML elements – namely, RadioSelect. This is a class that represents the “inner” HTML element of a widget.

class horizon.forms.fields.ThemableCheckboxChoiceInput(*args, **kwargs)[source]
class horizon.forms.fields.ThemableCheckboxInput(attrs=None, check_test=None)[source]

Checkbox widget which renders extra markup.

It is used to allow a custom checkbox experience.

render(name, value, attrs=None, renderer=None)[source]

Render the widget as an HTML string.

class horizon.forms.fields.ThemableChoiceField(*, choices=(), **kwargs)[source]

Bootstrap based select field.

widget

alias of ThemableSelectWidget

class horizon.forms.fields.ThemableDynamicChoiceField(add_item_link=None, add_item_link_args=None, *args, **kwargs)[source]
widget

alias of ThemableDynamicSelectWidget

class horizon.forms.fields.ThemableDynamicSelectWidget(attrs=None, choices=(), data_attrs=(), transform=None, transform_html_attrs=None)[source]
class horizon.forms.fields.ThemableDynamicTypedChoiceField(add_item_link=None, add_item_link_args=None, *args, **kwargs)[source]

Simple mix of ThemableDynamicChoiceField & TypedChoiceField.

class horizon.forms.fields.ThemableSelectWidget(attrs=None, choices=(), data_attrs=(), transform=None, transform_html_attrs=None)[source]

Bootstrap base select field widget.

render(name, value, attrs=None, renderer=None, choices=())[source]

Render the widget as an HTML string.

Form Views

class horizon.forms.views.ModalBackdropMixin(*args, **kwargs)[source]

Mixin class to allow ModalFormView and WorkflowView together.

This mixin class is to be used for together with ModalFormView and WorkflowView classes to augment them with modal_backdrop context data.

class horizon.forms.views.ModalFormMixin(*args, **kwargs)[source]
class horizon.forms.views.ModalFormView(*args, **kwargs)[source]

The main view class for all views which handle forms in Horizon.

All view which handles forms in Horiozn should inherit this class. It takes care of all details with processing SelfHandlingForm classes, and modal concerns when the associated template inherits from horizon/common/_modal_form.html.

Subclasses must define a form_class and template_name attribute at minimum.

See Django’s documentation on the FormView class for more details.

form_invalid(form)[source]

If the form is invalid, render the invalid form.

form_valid(form)[source]

If the form is valid, redirect to the supplied URL.

get_context_data(**kwargs)[source]

Insert the form into the context dict.

get_form(form_class=None)[source]

Returns an instance of the form to be used in this view.

get_object_display(obj)[source]

Returns the display name of the created object.

For dynamic insertion of resources created in modals, this method returns the display name of the created object. Defaults to returning the name attribute.

get_object_id(obj)[source]

Returns the ID of the created object.

For dynamic insertion of resources created in modals, this method returns the id of the created object. Defaults to returning the id attribute.

Forms Javascript

Switchable Fields

By marking fields with the "switchable" and "switched" classes along with defining a few data attributes you can programmatically hide, show, and rename fields in a form.

The triggers are fields using a select input widget, marked with the “switchable” class, and defining a “data-slug” attribute. When they are changed, any input with the "switched" class and defining a "data-switch-on" attribute which matches the select input’s "data-slug" attribute will be evaluated for necessary changes. In simpler terms, if the "switched" target input’s "switch-on" matches the "slug" of the "switchable" trigger input, it gets switched. Simple, right?

The "switched" inputs also need to define states. For each state in which the input should be shown, it should define a data attribute like the following: data-<slug>-<value>="<desired label>". When the switch event happens the value of the "switchable" field will be compared to the data attributes and the correct label will be applied to the field. If a corresponding label for that value is not found, the field will be hidden instead.

A simplified example is as follows:

source = forms.ChoiceField(
    label=_('Source'),
    choices=[
        ('cidr', _('CIDR')),
        ('sg', _('Security Group'))
    ],
    widget=forms.ThemableSelectWidget(attrs={
        'class': 'switchable',
        'data-slug': 'source'
    })
)

cidr = fields.IPField(
    label=_("CIDR"),
    required=False,
    widget=forms.TextInput(attrs={
        'class': 'switched',
        'data-switch-on': 'source',
        'data-source-cidr': _('CIDR')
    })
)

security_group = forms.ChoiceField(
    label=_('Security Group'),
    required=False,
    widget=forms.ThemableSelectWidget(attrs={
        'class': 'switched',
        'data-switch-on': 'source',
        'data-source-sg': _('Security Group')
    })
)

That code would create the "switchable" control field source, and the two "switched" fields cidr and security group which are hidden or shown depending on the value of source.

Note

A field can only safely define one slug in its "switch-on" attribute. While switching on multiple fields is possible, the behavior is very hard to predict due to the events being fired from the various switchable fields in order. You generally end up just having it hidden most of the time by accident, so it’s not recommended. Instead just add a second field to the form and control the two independently, then merge their results in the form’s clean or handle methods at the end.