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

3
  • Do you have your models set up correctly with foreign keys? Commented Jul 3, 2019 at 15:54
  • I think so; I have project.users as ManyToMany and project.company as ForeignKey Commented Jul 3, 2019 at 15:59
  • this may help you stackoverflow.com/questions/291945/… Commented Jul 3, 2019 at 15:59

2 Answers 2

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())
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this did the trick! I had to modify my views.py method a little: form = AddUserForm(project.company.pk, request.POST)
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.