dynamic form and model instances - what is the best method?

18 views
Skip to first unread message

Danny Blaker

unread,
Dec 18, 2018, 10:50:38 AM12/18/18
to Django users
Hi! I hope the following will help future django developers.

Scenario:

We need a form that allows the user to add and remove referees from a resume:  see (rough) snippet below:

(using materializecss)

     
<div class="row">
       
<div class="input-field col s6">
         
<input id="ref_name" type="text" class="validate">
         
<label for="ref_name">Reference Name</label>
        </
div>
       
<div class="input-field col s6">
         
<input id="ref_position" type="text" class="validate">
         
<label for="ref_position">Current Position</label>
        </
div>
       
<div class="row">
           
<a class="btn-floating btn-large waves-effect waves-light red" style="text-align:center;"><i class="material-icons">clear</i></a>   <!-- for removing the referee -->
       
</div>
      </
div>

     
<div class="row">
       
<div class="col s12">
         
<center>
           
<a class="btn-floating btn-large waves-effect waves-light red" style="text-align:center;"><i class="material-icons">add</i></a>
         
</center>
        </
div>
     
</div>

We have a resume model, and referees model with a many-to-many relationship like so:

class Resume(models.Model):
    first_name
= models.CharField(max_length=250)
    last_name
= models.CharField(max_length=250)
   
...


class Referees(models.Model):
    resume
= models.ForiegnKey(Resume, on_delete=CASCADE)
    name
= models.CharField(max_length=250)
    position
= models.CharField(max_length=250)


What is the best way to achieve this?


questions:

  • I'm assuming when user hits 'add', we'll need to clone a copy of the two input fields ('reference name' and 'current position'), and append it to the form? is using the java-script clone method best practice?
  • Is it best to create a new instance of the referee model each time a user hits "add", or create them all at once when the submit the form. (hit save)
  • When the user returns to edit view, the form will need to repopulate with all the new referees they added - what would be the best way to do this?
Note we're not using react or angular. Just pain old html / js / ajax.

All advice, solutions, suggestions most appreciated.

Cheers!





Reply all
Reply to author
Forward
0 new messages