views:

83

answers:

1

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?

A: 

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.

Jack M.
I was this far already, but wanted to make sure I was on the right track. How does this know to display the underlings that already exist under the current supervisor? Also, how can you create extra underling items using javascript? I guess you have to manually save every form and apply the relationships in your view, right? There's no way to create a ModelForm that manages its children, is there?
Nick Retallack
I left out a bunch of the boiler-plate code that you would have to write. If you'd like to have a variable number of Underlings, I would suggest ignoring formsets for now, and doing it through JavaScript or AJAX instead. Maybe even copy the way the admin interface does it. "Select from this list of Underlings, or add a new underling." That is really up to you to decide.
Jack M.
You want `inlineformset_factory`.
Daniel Roseman