Package: django-convenient-formsets
Django Convenient FormsetsThis Django app aims to make dynamic formsets convenient for users and
developers alike. It extends Django's built-in formset classes and includes
support for adding, deleting and ordering of forms in the browser. JavaScript
events are dispatched when forms are added, deleted or reordered, for executing
custom logic.Supported platformsDjango: 4.2+Python: 3.8+Tested desktop browsers: latest Chrome, latest Firefox, latest Edge,
latest Opera, latest SafariOther platform versions may work, but are not actively tested.InstallationInstall using pip:$pipinstalldjango-convenient-formsetsAdd toINSTALLED_APPS:INSTALLED_APPS=[# ...'convenient_formsets']Quick startCreate a formset in your Python code:fromconvenient_formsetsimportConvenientBaseFormSetfromdjangoimportformsclassEmailForm(forms.Form):email=forms.EmailField()EmailFormSet=forms.formset_factory(EmailForm,formset=ConvenientBaseFormSet,can_delete=True,can_order=True,)email_formset=EmailFormSet(prefix='email-formset')Render formset in your template and add JavaScript code for initialization:<!doctype html><html><head><!-- Include the formset's media -->{{email_formset.media}}<!-- Initialize a ConvenientFormset --><script>window.addEventListener('load',function(event){newConvenientFormset({'formsetPrefix':'{{email_formset.prefix}}','formsContainerSelector':'#email-formset #email-forms-container','formSelector':'.email-form','canAddForms':true,'addFormButtonSelector':'#email-formset #add-form-button','emptyFormTemplateSelector':'#email-formset #empty-form-template','canDeleteForms':true,'deleteFormButtonSelector':'#delete-form-button','canOrderForms':true,'moveFormDownButtonSelector':'#move-form-down-button','moveFormUpButtonSelector':'#move-form-up-button',});});</script></head><body><!-- Render formset using the following basic structure --><divid="email-formset"><divid="email-forms-container">{%foremail_forminemail_formset.forms%}<divclass="email-form">{{email_form.email}}{%ifemail_formset.can_delete%}{{email_form.DELETE}}<inputtype="button"id="delete-form-button"value="Delete">{%endif%}{%ifemail_formset.can_order%}{{email_form.ORDER}}<inputtype="button"id="move-form-up-button"value="Move up"><inputtype="button"id="move-form-down-button"value="Move down">{%endif%}</div>{%endfor%}</div><div><inputtype="button"id="add-form-button"value="Add another"></div><templateid="empty-form-template"><divclass="email-form">{{email_formset.empty_form.email}}{%ifemail_formset.can_delete%}<inputtype="button"id="delete-form-button"value="Delete">{%endif%}{%ifemail_formset.can_order%}{{email_form.ORDER}}<inputtype="button"id="move-form-up-button"value="Move up"><inputtype="button"id="move-form-down-button"value="Move down">{%endif%}</div></template>{{email_formset.management_form}}</div></body></html>UsageServer sideThe Python classesConvenientBaseFormSet,ConvenientBaseModelFormSetandConvenientBaseInlineFormSetextend Django's built-inBaseFormSet,BaseModelFormSetandBaseInlineFormSetby:Overridingdeletion_widgetfor theDELETEfield andordering_widgetfor
theORDERfield. They default to theforms.HiddenInputwidget in order to
hide them from the user.Including the JavaScript file in the formset'smediaattribute required
for dynamic formsets.Client sideSee the example in the Quick start guide above on how to render the formset in
your HTML template. Feel free to add some intermediate DOM elements if it suits
your template better, as long as you stick to the basic structure shown above.It is important that both the visible forms and the empty form follow the same
structure. A form also needs to be contained inside a single parent element,
denoted by theformSelectorparameter:<!-- Visible forms inside forms container --><divid="email-forms-container"><divclass="email-form"><!-- Form --></div></div><!-- Empty form inside template element --><templateid="empty-form-template"><divclass="email-form"><!-- Form --></div></template>ConfigurationCreating an instance of the JavaScript constructor functionConvenientFormsetallows a user to add, delete and reorder forms within the rendered formset.
When a user makes changes, the management form is updated accordingly. The
constructor function can be passed the parameters outlined below. In case
initialization fails, check the browser console for some helpful output.GENERALformsetPrefixThe formset's "prefix" attribute (required).formsContainerSelectorCSS selector for the DOM element that contains all the forms (required).formSelectorCSS selector for each form within "formsContainerSelector" (required).ADDING FORMScanAddFormsEnables adding of new forms (default: true).addFormButtonSelectorCSS selector for the DOM element that may be clicked to add an empty form (required if "canAddForms" is set).emptyFormTemplateSelectorCSS selector for the empty form <template> element (required if "canAddForms" is set).hideAddFormButtonOnMaxFormsHides the add button when reaching the maximum number of forms, by applying the "hidden" HTML attribute (default: true).DELETING FORMScanDeleteFormsEnables deleting of forms (default: false).deleteFormButtonSelectorCSS selector for the DOM element within "formSelector" that may be clicked to delete a form (required if "canDeleteForms" is set).ORDERING FORMScanOrderFormsEnables ordering of forms (default: false).moveFormDownButtonSelectorCSS selector for the DOM element within "formSelector" that may be clicked to move a form down among the visible forms (required if "canOrderForms" is set).moveFormUpButtonSelectorCSS selector for the DOM element within "formSelector" that may be clicked to move a form up among the visible forms (required if "canOrderForms" is set).EventsWhen adding, deleting or reordering forms, custom JavaScript events are
dispatched to allow for executing custom JavaScript code:convenient_formset:addedDispatched when a form is added to the formset.convenient_formset:removedDispatched when a form is removed to the formset.convenient_formset:movedDownDispatched when a form is moved downwards while reordering forms inside the formset.convenient_formset:movedUpDispatched when a form is moved upwards while reordering forms inside the formset.All events will contain theformsetPrefixparameter value in the event'sdetailproperty.These events can be handled in the following way:document.addEventListener('convenient_formset:added',(event)=>{if(event.detail.formsetPrefix==='email-formset'){// Handle event for a specific formset on the webpage}});document.addEventListener('convenient_formset:removed',(event)=>{// Handle event for any formset on the webpage});InternalsForm deletionis handled in either of the following ways:If a form includes aDELETEfield, the field's value is updated and the
form will be hidden by applying the "hidden" HTML attribute. The deletion
will then be handled server side.If the formdoes notinclude aDELETEfield, the form is removed from
the DOM altogether and will not be submitted to the server.Form orderingis handled by moving visible forms above the previous (up)
and below the next (down) for visual feedback, and by swapping the values of
theirORDERfields for the server side. This means that the original values
are kept, even when in-between forms are deleted. New forms will see the
initial value for theirORDERfield set to the last visible form'sORDERfield value + 1, as they're added to the bottom of all forms.LicenseThe scripts and documentation in this project are released under the
BSD-3-Clause License.