Formset and Inlines

PRO-only

ModelFormField

ModelFormField is a custom form field designed to integrate a single related form within a parent form. It’s suited for handling one-to-one relationships in Django models, enabling a nested form structure within a single parent form. This functionality streamlines the creation and editing of related model instances, facilitating user input and data handling in a cohesive manner.

Usage:

from viewflow.forms import ModelFormField

class UserProfileForm(forms.ModelForm):
    class Meta:
        model = UserProfile
        fields = ['bio', 'website']

class UserForm(forms.ModelForm):
    profile = ModelFormField(form_class=UserProfileForm)

    class Meta:
        model = User
        fields = ['username', 'email', 'profile']

In this example, ModelFormField is utilized to embed a UserProfileForm inside a UserForm, allowing the details of a user’s profile (bio and website) to be edited alongside the user’s basic information (username and email) in a unified form.

InlineFormSetField

InlineFormSetField is a custom form field for embedding a formset into a parent form. It is useful for managing one-to-many relationships in Django. By leveraging Django’s inline formset factory, this field facilitates the addition, modification, and deletion of multiple related instances directly from a single parent form.

Usage:

from viewflow.forms import InlineFormSetField

OrderItemFormSet = inlineformset_factory(
    Order, OrderItem, fields=('product', 'quantity'), extra=1)

class OrderForm(forms.ModelForm):
    items = InlineFormSetField(formset_class=OrderItemFormSet)

    class Meta:
        model = Order

        fields = ['customer', 'date']

In the provided example, ModelFormSetField is used to include an OrderItemFormSet within an OrderForm. This enables the management of multiple order items—each with its own product and quantity fields—within the context of a single order form, making it easier to create or update orders with their associated items.

InlineFormSetField could be used to manage m2m relations

from django.contrib.auth.models import User, Group
from django.forms.models import inlineformset_factory
from viewflow.forms import ModelForm, InlineFormSetField, AjaxModelSelect


GroupFormSet = inlineformset_factory(
    User,
    Group.user_set.through,
    fields=("group",),
    can_delete=False,
    extra=1,
    widgets={"group": AjaxModelSelect(lookups=["name__istartswith"])},
)


class UserForm(ModelForm):
    groups = InlineFormSetField(formset_class=GroupFormSet)

    class Meta:
        model = User
        fields = ["username", "first_name", "last_name"]