您需要django 内联表单集
鉴于:
f_set = inlineformset_factory(ModelB, ModelA, extra=1)
在模板中,假设您正在渲染 form_set,div
其 id 为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>
现在jquery
动态添加字段的部分:
$(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);
});
});
您可以在jsfiddle上对此进行测试。请注意,这仅在您呈现表单时才有效as_table