简体   繁体   中英

Increasing number of initial forms in a Django formset based on data in POST?

I have django formsets on my page, with several extra forms; I only want to show the user (initially) the forms with data already in them.

Currently I handle this by rendering 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 expose the ones 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 class .incorporate_directors_formset_invisible_div and increments TOTAL_FORMS count]

So far, so good. This works perfectly when the formset just contains initial data.

Now, my problem is that when some data is entered in a form, and the form validates as invalid, the INITIAL_FORMS value remains as it was originally, so the above code does not reveal the existing, but erroneous, form.

In my view, how do I increase the INITIAL_FORMS count to match the TOTAL_FORMS count sent back by the browser? Or, alternatively, otherwise ensure that the INITIAL_FORMS count is sufficiently large?

I have tried holding_formset.initial_forms = holding_formset.forms but that gives:

Traceback (most recent call last):

File "<debugger>", line 1, in <module>
holding_formset.initial_forms = holding_formset.forms
AttributeError: can't set attribute

It turns out that the solution is to use the formset's management form to modify 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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM