nyergler / nested-formset

Nest Django formsets for multi-level editing.
BSD 3-Clause "New" or "Revised" License
87 stars 21 forks source link

Demo For CreateView #21

Open kulbir opened 8 years ago

kulbir commented 8 years ago

Hi, How do I create nested-formset with CreateView? I tried your example. But that code does not show Employee's form. Am I missing something? Thanks

Here are my models

class Employee(models.Model):
    name = models.CharField(max_length=100)

class Salary(models.Model):
    salary = models.IntegerField()
    employee = models.ForeignKey(Employee)

class SalaryDivision(models.Model):
    salary = models.ForeignKey(Salary)
    percentage = models.IntegerField()

My View

class EmployeeCreateView(CreateView):
    model = Employee

    def get_form_class(self):

        return nestedformset_factory(
            Employee,
            Salary,
            extra=1,
            nested_formset=inlineformset_factory(
                Salary,
                SalaryDivision,
                extra=2,
                fields = '__all__'
            )
        )
nyergler commented 8 years ago

So a couple things come to mind.

First, you don't describe your template, but nested formset doesn't "magically" work like a normal form -- you have to iterate on over the nested forms. See nested-formset/demo/blocks/templates/blocks/building_form.html for an example of that in an update form.

Second (and probably more importantly for you), I don't believe that nested formsets don't support creating the "root" object along with children and grandchildren all in one go. Looking at the tests, they all start with a root object created ahead of time. My recollection is that the thing that's missing is attaching the ID of the newly created root object to its children at save time.

I'm not actively working on nested formsets these days, but I'd be happy to review a PR with tests if you wanted to add this.