GSoC Task 2 -- Pass custom arguments to forms in formset

About the Task

This task is simple to understand. So whenever you create a formset, earlier the one assumption was that you would provide Similar arguments to each form. It makes sense as essentially formset is a set of similar forms or a model. But the let’s say you have a model which takes saves the post along with the ID of the current user. You could not pass the single user parameter to let’s say the nth form in the formset. The task was to enable this functionality.

What I did in this task ??

The most exciting things turned out to be this feature was already implemented in the code. When I started reading the code for the formsets, after a thorough reading, I found this functionality to be present and can be achieved using the form_kwargs dictionary. I was scared and happy at the same time after figuring this out. Happy: obvious because my work was reduced :). Scared: because I almost wasted a week before I figured this and had no idea what my mentor will say. Ultimately, it all went well, read the whole story in the next blog, and it also has some tips on how to avoid this.

Technical description of the problem

Consider this example

class ServiceForm(forms.Form):
    option = forms.ModelChoiceField(queryset = ServiceOption.objects.none())
    rate = forms.DecimalField(widget = custom_widgets.SmallField())
    units = forms.IntegerField(min_value=1, widget=custom_widgets.SmallField())

    def __init__(self, *args, **kwargs):
        affiliate = kwargs.pop('affiliate')
        super(ServiceForm, self).__init__(*args, **kwargs)
        self.fields["option"].queryset = ServiceOption.objects.filter(affiliate=affiliate)

Here affiliate is the current user. Normally the user having something like this will initiate the form like

form = ServiceForm(affiliate=request.affiliate)

But if we use formsets, it’s challenging to pass the request to the individual form.

Here is the way this problem is solved

References

Report for the problem – Stack Post
Solution – Doc Link