I had a unique task for a project i was working on for work. I had to create a form that creates a object with the option to add child elements in one form/submit. I looked into formsets and a few other options but had a hard time saving the parent object to the child object.
So with my limited knowledge in django i did the best i could.
Parent: Laboratory Test
Child: Limit (Many To One Relationship)
Each time the “Add Limit” button is clicked a new “Limit” form gets added
- ES6 Template Literals
Basic Test Form with add limit Button, div for more forms and a save Button. notice we didn’t add submit input field. This is because we will need to save multiple forms at once so we created a custom “Save Forms” button to handle these forms.
Before handle submission we need to create some functions that will handle each form uniquely because they need to be sent to different views.
We will create a submitTest function that will handle the submission of our parent element (Main form) and a submitLimit that will be called for each limit we decide to add.
No that we have our functions we need a way to activate them. we do this by adding an event handler to out save forms button.
Handle save in view
We had to create 2 views to handle the two types of forms
So far our forms will save but the limit will not have a parent (Labtest) attached. the final trick is to use djangp signals
In our models.py this is how we handled it.