jrief / django-formset

The missing widgets and form manipulation library for Django
https://django-formset.fly.dev/
MIT License
317 stars 30 forks source link

Dynamically adding forms to collection #155

Closed boosh closed 1 month ago

boosh commented 1 month ago

I have a list of objects I want to display settings forms for. I want to avoid manually creating a form per object and instead retrieve the objects, then iterate over them instantiating a form for each one, e.g.:

class CampaignCollectionForm(SetProjectMixin, FormCollection):
    campaign = CampaignForm()

    def __init__(self, *args, **kwargs):
        project = kwargs.pop("project")

        channels = Channels.objects.filter(blah)
        for channel in channels:
            setattr(self, f"{channel.name}_form") = ChannelForm(channel=channel)

        super().__init__(*args, **kwargs)

This doesn't seem to work due to the work of FormCollectionMeta.__new__. Is it possible to add forms dynaically like this?