# Imports
from django.utils.safestring import mark_safe
from .base import Element
# Exports
__all__ = (
"FieldGroup",
"Fieldset",
)
# Classes
[docs]class FieldGroup(object):
"""A group of fields."""
[docs] def __init__(self, *fields, label=None, size=None):
"""Initialize a field group.
:param fields: List of bound or unbound field instances included in the group.
:param label: A label for the group.
:type label: str
:param size: The size of the group's columns.
:type size: int
"""
self.fields = list(fields)
self.label = label
self.size = size
def __iter__(self):
return iter(self.fields)
def __len__(self):
return len(self.fields)
[docs]class Fieldset(Element):
"""A fieldset within a form."""
[docs] def __init__(self, legend, fields=None, **kwargs):
super().__init__("fieldset", **kwargs)
self.fields = fields or list()
self.legend = legend
def __iter__(self):
return iter(self.fields)
def __len__(self):
return len(self.fields)
[docs] def add(self, field):
"""Add a field to the fieldset.
:param field: The field instance from the form.
:type field: BaseType[Field]
"""
self.fields.append(field)
[docs] @mark_safe
def to_html(self):
a = list()
a.append(self.get_open_tag())
a.append("<legend>%s</legend>" % self.legend)
for f in self.fields:
a.append(str(f))
a.append(self.get_close_tag())
return "\n".join(a)