Warm tip: This article is reproduced from stackoverflow.com, please click
django python

Pass variable from view to form in Django

发布于 2020-03-27 10:31:19

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

Questioner
user1314147
Viewed
18
Mahmood Al Rayhan 2019-07-04 00:04
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())