NestedForms

class NestedForms

A field that represents a set of forms, allowing for dynamic addition and removal of forms.

NestedForms(
    FormClass: 'type[Form]',
    *,
    min_items: int | None = None,
    max_items: int | None = None,
    default: Any = None,
    allow_delete: bool = False
)

Bases: Field

ArgumentDescription
FormClass

The class of the form to be used as a sub-form.

min_items

Minimum number of form in the set. Defaults to None (no minimum).

max_items

Maximum number of form in the set. Defaults to None (no maximum).

default

Default value for the field. Defaults to None.

allow_delete

Whether the form allows deletion of objects. If set to True, the form will delete objects of form when the "_destroy" field is present. Defaults to True.

This is a powerful field. The idea is to allow users to dynamically add or remove one or more instances of a subform.

class IngredientForm(f.Form):
    name = f.TextField()
    quantity = f.FloatField()


class RecipeForm(f.Form):
    title = f.TextField()
    instructions = f.TextField()
    ingredients = f.NestedForms(IngredientForm)

In a database this is equivalent to a one-to-many relationship (in this example one Recipe has many Ingredients).

There is a lot to unpack, so this field has its own section: Nested Forms.