简体   繁体   中英

How do I submit multiple forms with a single submit button in django?

I have managed to create the forms I need using modelformset_factory.

avaluos = Avaluo.objects.filter(Estatus__contains='CONCLUIDO',Factura__isnull=True)
FacturaFormset = modelformset_factory(Avaluo,form=FacturaForm,extra=0)

Currently this is generating the following HTML for each of the rows found:

<form id="id-FacturaForm" class="blueForms" method="post">[..]</form>
<form id="id-FacturaForm" class="blueForms" method="post">[..]</form>
<form id="id-FacturaForm" class="blueForms" method="post">[..]</form>

I want to submit all the forms using a single submit button.

Any ideas?

UPDATE

I ended up using django-crispy-forms which allowed me to gerate inputs for each row, and then I just manually added the form and submit.

   self.helper.form_tag = False


{{example_formset.management_form }}
       {% for a,b in olist %}
{{ b.id }}
<tr>
    <td style="width:10px;"> {% crispy b %} </td>
    <td> {{a.id}} </td>     
</tr>
{% endfor %} 

Read more into model formsets . You don't need to have separate form tags, it's the whole point of using a formset.

<form method="post" action="">
    {{ factura_formset.management_form }}
    <table>
        {% for form in factura_formset %}
            {{ form }}
        {% endfor %}
    </table>
</form>

Also, every time you use the id attribute more than once on a page… a developer cries themselves to sleep somewhere in the world.

I suspect you will need to do it using Ajax - otherwise as soon as one form is submitted you will not be able to go the other way.

There are a few jQuery form libraries that should make it relatively straightforward. For example, http://malsup.com/jquery/form/ .

It would look something like:

$('#button-id').click(function() {
  $('.blueForms').ajaxSubmit();
});

Of course, you'll then need to deal with error handling and waiting for all the forms to have submitted.

If you're trying to create many instances of the "same" form (this is, they all look equal), as if it were one of many childs belonging to a single, master element, you don't actually need to create a form tag for each of the formsets.

If I'm not mistaken, you're trying to edit many facturas for a single avaluo object. Am I right? The representation would be a single "avaluo" form with many inline formsets, one for each "factura".

Check out the inline formsets factory instead of the modelformset factory.

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