Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Nested Inline Formsets to Populate Multilevel Nested Form

I'm trying to solve a problem. I have a model hierarchy like this:

class Task(models.Model):
    name = models.CharField(max_length=255)
    number_of_steps = models.IntegerField()

class StepGroup(models.Model):
    task = models.ForeignKey(Task)
    init_date = models.DateField()

class Step(models.Model):
    group = models.ForeignKey(StepGroup)
    name = models.CharField(max_length=255)

I must write a dialog where I create a number of StepGroups. I want the form to be nested because I want to give the user the ability to edit steps that belong to a StepGroup (1-to-many) that belong to a task (1-to-many). So, I want the nested forms to be served in views, instead of in django-admin.

I want to do it with Django inlineformset_factory. However, Django inlineformset_factory only allows one level of nested form. In my case the nesting was 2 levels. Can I achieve it by overriding the BaseInlineFormset? If I can achieve the nested form can I have more depth (3 levels or more) of nested forms?

This is the way I need the form (the number of steps in each group is set by the "number_of_steps" field in the Task model):

+-----------------------------------+
| STEP GROUP 1                      |
|                                   |
| Init date: _____________          |
|                                   |
| Step 1: ________________          |
| Step 2: ________________          |
| Step 3: ________________          |
|                                   |
+-----------------------------------+
| STEP GROUP 2                      |
|                                   |
| Init date: _____________          |
|                                   |
| Step 1: ________________          |
| Step 2: ________________          |
| Step 3: ________________          |
|                                   |
+-----------------------------------+
|                                   |
|             +-------------------+ |
|             | Create step group | |
|             +-------------------+ |
+-----------------------------------+
like image 263
César García Tapia Avatar asked Sep 07 '25 10:09

César García Tapia


1 Answers

It is possible. I presented it on the Pycon Ru 2021, and start to write articles about it:

https://dev.to/danilovmy/django-nested-inline-redering-4pfg

Shortly:

You can create Formset, One field is this Formset - it is other Formset. Here is a little bit hard plate, how to achieve correct id for every fields. You need also override "is_changed" for field. And the save method.

Biggest problem in Nested - multiuser work. If one user change something, that right now changed other user - you can get complex bug in DB-consistency

like image 116
Maxim Danilov Avatar answered Sep 10 '25 15:09

Maxim Danilov