Adding a formset_kwargs keyword argument to BaseFormSet

Hi,

I find it useful when using formsets to define and set an attribute that can be used during validation.

class MyFormSet(BaseFormSet):
    useful_attribute = None

    def clean(self):
        super().clean()

        # validation code using self.useful_attribute...


# usage in a view...

    the_formset = formset_factory(MyForm, formset=MyFormSet, extra=0)

    bound_formset = the_formset(initial=initial_results,
    	form_kwargs=form_kwargs)

    bound_formset.useful_attribute = useful_value

But I don’t think this is very pythonic. I feel that I should be overriding MyFormSet.__init__() with a dict of kwargs passed to __init__() when I am binding the formset.

I’m wondering if formset_kwargs could be added to BaseFormSet to follow the form_kwargs pattern. The suggested usage would be something like this:

class MyFormSet(BaseFormSet):
    def __init__(self, useful_attribute, *args, **kwargs):
        self.useful_attribute = useful_attribute
        super().__init__(*args, **kwargs)

    def clean(self):
        super().clean()

        # validation code using self.useful_attribute...


# usage in a view...

    the_formset = formset_factory(MyForm, formset=MyFormSet, extra=0)

    bound_formset = the_formset(initial=initial_results,
    	form_kwargs=form_kwargs,
    	formset_kwargs={"useful_attribute": useful_value})

The kwargs provided in formset_kwargs would then be passed to MyFormSet when it is instantiated.

Hi @richardbrockie.

In this case you’d pass useful_attribute directly no… :thinking:

class MyFormSet(BaseFormSet):
    # If useful_attribute is a kwarg it comes after *args
    def __init__(self, *args, useful_attribute=None,  **kwargs):
        self.useful_attribute = useful_attribute
        super().__init__(*args, **kwargs)

Then:

    the_formset = formset_factory(MyForm, formset=MyFormSet, extra=0)

    bound_formset = the_formset(
        initial=initial_results,
    	form_kwargs=form_kwargs,
    	useful_attribute=useful_value
    )

formset_factory() gives you back a FormSet class ready to be instantiated directly, so you pass whatever args and kwargs you want, without the need for the indirection.

Am I misunderstanding what you’re aiming at perhaps?

@carltongibson

You understood correctly what I’m trying to do. I had completely missed the implication of what formset_factory returns. It’s obvious now :crazy_face:

Thanks!