Increasing the number of initial forms in a Django form set based on data in POST?

I have django formsets on my page with a few additional forms; I want to show the user (initially) forms with already existing data.

I am currently processing this, creating each form as hidden:

{% for form in incorporate_directors_formset %} <tbody class="incorporate_directors_formset_div subform incorporate_directors_formset_invisible_div" id="incorporate_directors_formset_div_{{ forloop.counter }}"> {{ form }} </tbody> <tr class="magic-last-row invisible"><td colspan=2><div></div></td></tr> {% endfor %} 

[ .incorporate_directors_formset_invisible_div just sets display:none; ]

then using javascript to open those that already have data:

  for(i = directors_initialforms.val(); i > 0; i--) director_form_to_display($('.incorporate_directors_formset_invisible_div').first(), false); 

[ director_form_to_display pretty much just removes the .incorporate_directors_formset_invisible_div class and increases the TOTAL_FORMS count]

So far so good. This works great when the form set simply contains the source data.

Now my problem is that when some data is entered into the form and the form is checked as invalid, the value of INITIAL_FORMS remains the same as it was originally, therefore the above code does not show the existing but erroneous form,

In my opinion, how to increase the INITIAL_FORMS account to match the TOTAL_FORMS account sent by the browser? Or, conversely, otherwise make sure that the number of INITIAL_FORMS is large enough?

I tried holding_formset.initial_forms = holding_formset.forms but this gives:

 Traceback (most recent call last): File "<debugger>", line 1, in <module> holding_formset.initial_forms = holding_formset.forms AttributeError: can't set attribute 
+4
source share
1 answer

It turns out that the solution is to use the form management form to change the actual request data:

 from django.forms.formsets import INITIAL_FORM_COUNT if formset.initial_form_count() < formset.total_form_count(): manform = formset.management_form prefixed_name = manform.add_prefix(INITIAL_FORM_COUNT) manform.data[prefixed_name] = formset.total_form_count() 
0
source

Source: https://habr.com/ru/post/1398030/


All Articles