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 %}
<table>
<tr>
<td>
<span class="answer_span">{{ answer.answer }} {{ answer.answer.errors }}</span>
</td>
……etc…….
</tr>
</table>
[/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.

By David

I am a supporter of free software and run Burke Software and Consulting LLC. I am always looking for contract work especially for non-profits and open source projects. Open Source Contributions I maintain a number of Django related projects including GlitchTip, Passit, and django-report-builder. You can view my work on gitlab. Academic papers Incorporating Gaming in Software Engineering Projects: Case of RMU Monopoly in the Journal of Systemics, Cybernetics and Informatics (2008)

1 comment

  1. I tried the same method. But when i post the new forms then all newly added rows are going back as empty forms and no values in them. Could you tell me what I may be missing?

    Like

Leave a reply to sushovan Cancel reply