Search code examples
djangodjango-formsinline-formset

Django - Modify Inlineformset Delete button


I do a custom UI/UX for an inlineformset.

By default the inlineformset widget has a delete button.

I wan to add and remove forms from inlineformset dynamic using javascript. In some cases the delete is just a button instead of the checkbox, in other cases is in a modal window.

When a user click delete the form is removed from the page with javascript.

So, I try to do this without using the default widget, render fields in the template, but I don't know how to tell Django witch fields to remove and if is necessary to readjust the ids and names of the fields.


Solution

  • My solution for this problem was to just overwrite the template_name of CheckboxInput widget class:

    widgets.CheckboxInput.template_name = 'widgets/delete.html'
    

    I added that in my {app}/widgets.py that hosts my custom widgets. As I am using the same format accross my app, I think it's the only way to go.

    {app}/templates/widgets/delete.html:

    <div class="checkbox checkbox-styled">
    <label>
        <input name={{ widget.name }} type="checkbox" value="true" {% if widget.attrs.checked == True %}checked{% endif %}>
        <span>Delete</span>
    </label>
    </div>
    

    If it would not have been the inlineformset_factory then the best way was to create a new class extending BaseFormSet and to overwrite the widget in add_fields method like suggested in this answer.