In Uncategorized

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.

Objects:

Parent: Laboratory Test

Child: Limit (Many To One Relationship)

Final Product

Each time the “Add Limit” button is clicked a new “Limit” form gets added

Prerequisites 

  • Dajngo
  • Signals
  • JavaScript Jquery
  • Ajax
  • ES6 Template Literals
HTML

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.

Add Limit

Now in our JavaScript we will need to add an event handler that adds a new form to the “limits-wrapper” div each time we click the “Add Limit button”

Submit 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

Django Signal

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.

Contact Us

We're not around right now. But you can send us an email and we'll get back to you, asap.