How do you make a Django Form for a model and all of its children following a particular foreign key?
For example, lets say you want to create a ModelForm for Supervisor that also allows you to create or update 3 or more Underlings in the same form.
from django.db import models class Supervisor(models.Model): name = models.CharField(max_length=100) class Underling(models.Model): supervisor = models.ForeignKey(Superisor, related_name="underlings") name = models.CharField(max_length=100)
This should be pretty standard, right? Just make a FormSet for the underlings, and... then what? The Django Admin interface does it, so how do I do it?
First you would define your ModelForm for Underlings:
class UnderlingForm(forms.ModelForm): class Meta: model = Underling
Then you would create a FormSet of UnderlingForms:
UnderlingFormSet = formset_factory(UnderlingForm, extra=3) # 3 Underlings.
Then you instantiate and loop over them (or pass them to a template context):
formset = UnderlingFormSet() for form in formset.forms: print form.as_table()