jazzband / django-formtools

A set of high-level abstractions for Django forms
https://django-formtools.readthedocs.io
BSD 3-Clause "New" or "Revised" License
794 stars 135 forks source link

Form throws TypeError using get_form_kwargs within DFT but no errors passing kwargs outside it #197

Open quinceleaf opened 3 years ago

quinceleaf commented 3 years ago

Using django-formtools 2.3, Django 3.2

Issue: form used outside of DFT can be passed kwarg without issue, but same form throws TypeError when kwarg passed using get_form_kwargs within DFT

I am using DFT on a 2-part form for creating a bill-of-materials. For updating, I use standard UpdateViews with only the parts of the form user wants to modify. So I am able to see the forms/formsets working on their own, as well as when used by DFT.

My issue is when passing kwargs using get_form_kwargs to modify the queryset of one field:

< in forms.py >

class BillOfMaterialsLineForm(common_forms.BaseModelForm):
    def __init__(self, *args, **kwargs):
        self.product = kwargs.pop("product", None)
        super(BillOfMaterialsLineForm, self).__init__(*args, **kwargs)

        if self.product:
            self.fields["item"].queryset = models.Item.objects.exclude(
                version_key=self.product.version_key
            )
            self.fields["item"].widget.queryset = models.Item.objects.exclude(
                version_key=self.product.version_key
            )

< in views.py >

        formset = self.form_class(
            instance=self.object,
            queryset=models.BillOfMaterialsLine.objects.filter(
                bill_of_materials=self.object
            ),
            prefix="lines",
            form_kwargs={"product": self.object.product},
        )
    def get_form_kwargs(self, step, **kwargs):
        kwargs = super(BillOfMaterialsWizardCreateView, self).get_form_kwargs(step)
        if step == "lines":
            kwargs["product"] = models.Product.objects.get(id=self.kwargs["pk"])
        return kwargs

Not sure if I'm doing something incorrectly or if this is an error in DFT. I believe my use of get_form_kwargs is structured correctly, but I've only been able to locate a single example so that may be the problem.

Any feedback would be welcome