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?

Answers


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()

Since you'll also have a SupervisorForm in the same view, I'd suggest having a glance at the prefix option too. If you are still left with questions about Formsets, here is the official docs.


Need Your Help

Handling server being aware if iPhone app is running (heartbeat)

ios iphone sockets apple-push-notifications

I am not sure how to best implement keeping our server informed that our iPhone application is currently running (even when in the background). There are a few different options but there is some c...

How do I delete a datarow from a datarow array?

c# linq datarow

I am looping through a array of datarows and when a particular random item is not valid I want to remove that item and get the new total to get another random item.