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 StepGroup
s. 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 | |
| +-------------------+ |
+-----------------------------------+
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With