Dynamic Formset: How to add forms?

Hi all,

I have created a set of forms using the formtools NamedUrlSessionWizardView. One of the forms in the wizard, is a django ModelForm, which contains another ModelForm, as an inline formset:

class ActivityForm(ModelForm, CrispyForm):
    class Meta:
        model = Activity
    def adjustLayout(self):
                Fieldset('Add Activity Steps',

class ActivityStepForm(ModelForm, CrispyForm):
    class Meta:
        model = ActivityStep

    def __init__(self, *args, **kwargs):
        self.formtag_prefix = re.sub('-[0-9]+$', '', kwargs.get('prefix', ''))
        super().__init__(*args, **kwargs)

    def adjustLayout(self):
        self.helper.template = f'{TEMPLATE_PACK}/table_inline_formset.html'
        self.helper.all().wrap_together(Div, css_class=f'formset_row-{self.formtag_prefix}')

ActivityStepFormSet = inlineformset_factory(
    extra=1,          # number of empty forms to display
    can_delete=False   # show a checkbox in each form to delete the row

The form is shown correctly, and contains a single form within the form set.

However, I want to add the ability of more forms to be added by the user.
The javascript in django-dynamic-formset seems to not work with jQuery used by crispy-forms.

What is the “most recent” way to achieve dynamic formsets?

We never found a need for using any third-party packages for that.

Before HTMX, we used something that was quite “HTMX-like” in that we would invoke a view to render the new form to be added and then modified the management form directly.

If we needed to do something like that now, we would definitely use HTMX for that.

(Note: Part of the reason why we rely upon server-side rendering for this is because the application doing that is actually using three levels of nested formsets and we need to track the prefixes properly. We found it a lot easier to manage this using Django templates than trying to manage it using JavaScript.)

Thanks for your reply. I am not sure how to use HTMX for that.

I was reading this: Django Formsets Tutorial - Build dynamic forms with Htmx
But the result is a collection of forms (each one having a submit button), and not a formset.
Is there any other tutorial that uses HTMX in a different way?

I am using a wizard from formtools, and this complicates the views a bit.

I don’t know about any tutorials, but there’s not much difference between the two cases. You’re still adding some HTML to the current page - from the perspective of HTMX it doesn’t matter if it’s a full form (including the <form> tag) or just a div containing the new row for the formset.

Finally, I implemented it by adding some javascript code in the template. The biggest problem was getting jQuery to work, as django places it in window.django.