Adding new form in a formset

Everything I read about adding a new form to a formset with javascript involves cloning an existing form. This is a terrible method, what if the initial forms are 0? What about initial data? Here’s IMO better way to do it that uses empty_form, a function Django gives you to create a form where i is __prefix__ so you can easily replace it. Add this under you “Add new FOO” button. In my case I have a question_form with many answers (answers_formset). [html] var form_count_{{ question_form.prefix }} = {{ answers_formset.total_form_count }}; $(‘#add_more_{{ question_form.prefix }}’).click(function() { var form = ‘{{answers_formset.empty_form.as_custom|escapejs}}’.replace(/__prefix__/g, form_count_{{ question_form.prefix }}); $(‘#answers_div_{{ question_form.prefix }}’).append(form); form_count_{{ question_form.prefix }}++; $(‘#id_{{ answers_formset.prefix }}-TOTAL_FORMS’).val(form_count_{{ question_form.prefix }}); }); [/html] This creates you empty_form right in javascript, replaces the __prefix__ with the correct number and inserts it, in my case I made an answers_div. See empty_form.as_custom, you could just do empty_form but that would just give the you basic form html. I want custom html. Make a separate template for this. Here’s mine but this just an example. [html] {{ answer.non_field_errors }} {% for hidden in answer.hidden_fields %} {{ hidden }} {% endfor %}

......etc.......
{{ answer.answer }} {{ answer.answer.errors }}

[/html] In your original template you can add the forms like this {% include “omr/answer_form.html” with answer=answer %} But for the as_custom you need to edit your form itself to add the function. [python] def as_custom(self): t = template.loader.get_template(‘answer_form.html’) return t.render(Context({‘answer’: self},)) [/python] I find this method far more stable than trying to clone existing forms. It seems to play well with the javascript I have in some of my widgets. Clone on the other hand gave me tons of trouble and hacks needed to fix it.