Reputation: 362
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
Upvotes: 0
Views: 1941
Reputation: 733
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
Upvotes: 0
Reputation: 662
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())
Upvotes: 2