0

I am building a simple task management system, where a Company can have multiple projects, and each company has employees. I want a form that allows managers to add users to projects, with the constraint that the available users belong to the company.

I am passing the variable company_pk from the view to the form, but I am not sure how to set/access the variable outside the init finction.

class AddUserForm(forms.Form):
    def __init__(self, company_pk=None, *args, **kwargs):
        """
        Intantiation service.
        This method extends the default instantiation service.
        """
        super(AddUserForm, self).__init__(*args, **kwargs)
        if company_pk:
            print("company_pk: ", company_pk)
            self._company_pk = company_pk

    user = forms.ModelChoiceField(
        queryset=User.objects.filter(company__pk=self._company_pk))
form = AddUserForm(company_pk=project_id)

As mentioned, I want to filter the users to only those belonging to a given company, however I do not know how to access the company_pk outside of init. I get the error: NameError: name 'self' is not defined

user1314147
  • 174
  • 1
  • 5
  • 25

2 Answers2

2
class AddUserForm(forms.Form):
    def __init__(self, company_pk=None, *args, **kwargs):
        super(AddUserForm, self).__init__(*args, **kwargs)
        self.fields['user'].queryset = User.objects.filter(company__pk=company_pk)

    user = forms.ModelChoiceField(queryset=User.objects.all())
  • Thanks, this did the trick! I had to modify my views.py method a little: form = AddUserForm(project.company.pk, request.POST) – user1314147 Jul 04 '19 at 18:24
0

You must use self.fields to override the user's queryset

class AddUserForm(forms.Form):
    def __init__(self, company_pk=None, *args, **kwargs):
        super(AddUserForm, self).__init__(*args, **kwargs)
        if company_pk:
            self.fields['user'].queryset = User.objects.filter(company__pk=company_pk))

for more information about it. check this out How to dynamically filter ModelChoice's queryset in a ModelForm

Bob White
  • 733
  • 5
  • 20