[Answer]-How to have a ModelForm with a dynamic amount of related objects?

1👍

You require django inline formset

In view:

f_set = inlineformset_factory(ModelB, ModelA, extra=1)

In template lets suppose you are rendering form_set in a div whose id is one_to_many:

<form>
   <div id="one_to_many">
       {{f_set.as_table}}
   </div>
</form>

#This will render some thing like this
<form>
    <div id="one_to_many">
        <table>
            <tr>
               <th>
                   <label for="id_form-0-field_name">Field Name:</label>
               </th>
               <td>
                  <input id="id_form-0-field_name" type="text" name="form-0-field_name" value="" maxlength="100" />
                  <input type="hidden" name="form-0-id" value="1" id="id_form-0-id" />  
                </td>
            </tr>
        </table>
        <input type="button" value="Add More Field" id="add_more">
    </div>
</form>

Now the jquery part to add field dynamically:

$(document).ready(function(){
        $('#add_more').click(function(){
            var tbl = $('#one_to_many').children('table');
            var last_id = parseInt(tbl.find('input[type=hidden]').last().val());
            var next_id = last_id + 1;
            htm = '<tr><th><label for="id_form-'+last_id+'-field_name">Field Name:</label></th><td><input id="id_form-'+last_id+'-field_name" type="text" name="form-'+last_id+'-field_name" value="" maxlength="100" /><input type="hidden" name="form-'+last_id+'-id" value="'+next_id+'" id="id_form-'+last_id+'-id" /></td></tr>'
            tbl.find('tr').last().after(htm);

        });    
    });

You can test this on jsfiddle. Note this will only work if you render your form as_table

Leave a comment