[Fixed]-Passing arguments to a form obtained by 'getattr()'

1👍

This doesn’t have anything to do with you using getattr, the problem is in your __init__ method. You need to pop user before calling super().

def __init__(self, *args, **kwargs):
    self.user = kwargs.pop('user', None)
    super(MyForm, self).__init__(*args, **kwargs)

You should instantiate the form as you usually do:

form = MyForm(user=request.user)

It doesn’t matter whether MyForm is declared in the same module:

class MyForm(forms.Form):
   my_field = forms.CharField()

form = MyForm(user=request.user)

or if you get the form class dynamically using getattr

 MyForm = getattr(forms, service.form)
 form = MyForm(user=request.user)

Leave a comment