I am trying to implement a django form set (where the user can dynamically add / remove forms from a form set).
I use JS to add new lines (using empty_form):
$("#add-item").click(function(e){ e.preventDefault(); var count = parseInt($('#id_form-TOTAL_FORMS').val()); $('.invoice-items').append($('#empty_invoice_item').html().replace(/__prefix__/g, count)); $('#id_form-TOTAL_FORMS').attr('value', count+1); $(".invoice-items .invoice-item .col-lg-9 .form-group:last-child").last().append('<a href="#" class="delete-item"><i class="glyphicon glyphicon-remove"></i></a>') });
I also use JS to set the DELETE flag for certain forms. Everything is submitted to the submission.
My view code (part):
invoice_form = InvoiceForm() invoice_item_helper = InvoiceItemHelper InvoiceItemFormset = formset_factory(InvoiceItemForm, extra=0, max_num=15, validate_max=True, min_num=1, validate_min=True, can_delete=True) formset = InvoiceItemFormset() if request.method == 'POST': invoice_form = InvoiceForm(request.POST) formset = InvoiceItemFormset(request.POST)
The problem is that django always displays all forms in the form set, even those that are marked for deletion. Thus, even in my invoice form, something is wrong and it is not verified, it will display an invoice form with an error message and all forms (again).
How to delete all forms marked for deletion in the if request.method == 'POST': block? Is it possible?
source share