Deleting form from django formset


I am trying to implement a django formset (where user may dynamically add/remove forms from formset).

I use JS to add new rows (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 DELETE flag on specific forms. Everything is passed to the view.

My view (part) code:

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, django always displays all forms in the formset, even those marked for deletion. So, even there is something wrong in my invoice form and it doesn't validate, it will show invoice form with error message AND all forms (once again).

How can I remove completely forms which are marked for deletion in if request.method == 'POST': block? Is it possible?


It's dependent on how you render the forms, but you can check the field <a href="https://github.com/django/django/blob/master/django/forms/formsets.py#L19" rel="nofollow">form.DELETE</a> in the template and if it's set, render that form hidden for display and the data will be passed along until the data is processed (when all other forms are valid). It will also make sure form prefixes and indexes for the formset is intact.

When a formset is validated it will ignore forms marked for deletion. <a href="https://github.com/django/django/blob/master/django/forms/formsets.py#L304" rel="nofollow">formset.is_valid</a>

You can also pick up which forms are deleted in the view using <a href="https://github.com/django/django/blob/master/django/forms/formsets.py#L213" rel="nofollow">deleted_forms</a> and perhaps process them, still you will have to rebuild the whole formset without the deleted forms to maintain indexes and the count of forms. I personally found out that doing that is complex and leads to complicated code.


Django provides a for-deletion feature which should enable proper deletion of your form: <a href="https://docs.djangoproject.com/en/1.8/topics/forms/formsets/#can-delete" rel="nofollow">https://docs.djangoproject.com/en/1.8/topics/forms/formsets/#can-delete</a>

The form-X-DELETE needs to be set to some value evaluating to true though. The default is on, as you can see in the example from the documentation:

>>> data = { ... 'form-TOTAL_FORMS': '3', ... 'form-INITIAL_FORMS': '2', ... 'form-MAX_NUM_FORMS': '', ... 'form-0-title': 'Article #1', ... 'form-0-pub_date': '2008-05-10', ... 'form-0-DELETE': 'on', ... 'form-1-title': 'Article #2', ... 'form-1-pub_date': '2008-05-11', ... 'form-1-DELETE': '', ... 'form-2-title': '', ... 'form-2-pub_date': '', ... 'form-2-DELETE': '', ... }

So if that is not working, perhaps you are not actually sending a value to your form-X-DELETE? Do note that you need to specify the actual form data when sending the delete. Simply sending the form number alone is not enough identification for Django to accept it.


  • Sequentially run commands in bash script
  • How would I make a polygon based on the relative positions of markers in google maps?
  • Getting nil from standardUserDefaults,
  • Django IN query as a string result - invalid literal for int() with base 10
  • Working with django : Proxy setup
  • SQL Worksheet is not displaying in SQL Developer
  • Oracle REF can't go through
  • Questions related to Garbage Collector and finalize() method
  • How do I change the names of buttons on a message box?
  • Scheme procedure to compute the nth repeated application of a function?
  • Unity Resources.load() won't work with external dll
  • Update all WooCommerce product prices to 2 decimals in database
  • Pandas time series data Index from a string to float [duplicate]
  • Checking for valid enum types from protobufs
  • Fortran function variable length string return
  • separate tokens in batch file
  • Keep rows with certain values always at the bottom while sorting in jquery tablesorter plugin
  • Arraylist of strings into one comma separated string
  • Spotify cocoalibspotify offline status set to 1 but all tracks stuck at waiting
  • How do I use libcurl to printf a remote FTP directory listing?
  • How to check if a database and tables exist in sql server in a vb .net project?
  • Multiplying polynomials/simplifying like terms
  • java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/SpringDispatcher-ser
  • Add font awesome icon to custom add to cart button in Woocommerce 3
  • Floating parent div grows to hypothetical width of floating child div
  • Google Spreadsheet Script to Blink a range of Cells
  • Terminal run dalvikvm with am.jar
  • how to snap two objects in runtime in unity?
  • Another “Cannot make static reference…” Question
  • How to handle div that is created dynamically in a table
  • read part of h5 dataset python
  • Send array to next viewcontroller iOs xcode [duplicate]
  • Make checkout phone field optional for specific countries in WooCommerce
  • Codeigniniter insert data through models and controller
  • Python Flask - GUI for client
  • PHP Permalinks.. how to change?
  • What does the “id” field in an Android “Google Play Music” broadcast intent correspond to?
  • How to mutate multiple variables without repeating codes?
  • ReferenceError: TextEncoder is not defined
  • How to check if object is null in Java?