Here's the way I'm doing it:
{{ formset.management_form }}
<table>
{% for form in formset.forms %}
{{ form }}
{% endfor %}
</table>
<a href="javascript:void(0)" id="add_form">Add Form</a>
And here's the JS:
var form_count = {{formset.total_form_count}};
$('#add_form').click(function() {
form_count++;
var form = '{{formset.empty_form|escapejs}}'.replace(/__prefix__/g, form_count);
$('#forms').append(form)
$('#id_form-TOTAL_FORMS').val(form_count);
});
What specifically bothers me is that I had to write that escapejs
template tag myself. It just strips all newlines and escapes any single quotes so that it doesn't mess up my string. But what exactly did the Django makers expect us to do in this situation? And why do they have this TOTAL_FORMS
hidden field, when they could have just used an array like <input name="my_form_field[0]" />
and then counted its length instead?
empty_form
with__prefix__
so that you could replace it, supposedly. – Lowther.empty_form
- nice and short. Thanks! – Cakewalk</script>
will break out of the script even when it's inside a string. Although, I believe different browsers will handle<scripts>
differently when injected via JS (some will execute it, some won't). – Lowther__prefix__
must be replaced withform_count - 1
. It starts with 0, not 1. – Teofilateosinte