How do I pass arguments to django forms?

I want to filter form fields querysets based on the user selected. Therefore, I want to pass user as argument to the form in order to filter fields querysets in the form's __init__ method. When I pass any arguments to the form I get the following error.

class UserDetailView(LoginRequiredMixin, FormMixin, DetailView):
    model = TbUser
    form_class = TbPeopleEntranceRightForm

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        form = TbPeopleEntranceRightForm(user=self.object)
        context['form'] = form
        return context

__init__() got an unexpected keyword argument 'user'

how do I pass the argument correctly, and how I get it in the __init__ form method?

Update:


class TbPeopleEntranceRightForm(forms.ModelForm):

    def __init__(self, user, **kwargs):
        super().__init__(**kwargs)
        print(user)
        # Use `self.user` here or in some other methods.

__init__() missing 1 required positional argument: 'user'

2 answers

  • answered 2021-06-23 07:07 ruohola

    You need to add the parameter to the form's __init__ method:

    class TbPeopleEntranceRightForm(forms.ModelForm):
    
        ...
    
        def __init__(self, user=None, **kwargs):
            super().__init__(**kwargs)
            self.user = user
            # Use `self.user` here or in some other methods.
    

    Also, the correct way to then pass the user argument to the form is to override get_form_kwargs in the view, like @MojixCoder showed.

  • answered 2021-06-23 07:08 MojixCoder

    don't do it in get_context_data, it's made for something else.
    Use get_form_kwargs instead:

    class UserDetailView(LoginRequiredMixin, FormMixin, DetailView):
        model = TbUser
        form_class = TbPeopleEntranceRightForm
    
        def get_form_kwargs(self):
            kwargs = super().get_form_kwargs()
            kwargs["user"] = self.object
            return kwargs  
    

    And in your forms.py:

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