Home > other >  How to pass extra information to a form in Django
How to pass extra information to a form in Django

Time:11-22

I have the following form which should return a queryset of Cashpool where cashpool__name=request.user.company.cashpool. To execute the correct query, it needs information from the view.

# views.py

class AddAccountForm(forms.Form):

    # The entity on whose behalf the account shall be added
    company = forms.ModelChoiceField(queryset=Company.objects.get(name=....))

    ...

Is there any way to pass an extra argument to the form in the view to make the user object available in the form so it can get the correct queryset somehow?

# forms.py

def add_account(request):

    # Return the form on get request
    if request.method == 'GET':
        form = AddAccountForm()

    ...

CodePudding user response:

This is how you can do to pass some filtered initial data to a form in Django. Simply override the base_fields attribute of the form.

views.py

def add_account(request):
    if request.method == 'GET':
        # Retrieve the form initial value
        company_name = request.user.company.name
        cashpool= Cashpool.objects.get(name=company_name)
        
        # Override the AddAccountForm company field
        AddAccountForm.base_fields['company'] = forms.ModelChoiceField(
        queryset=cashpool)

        # Instantiate the form now
        form = AddAccountForm()

        # Other code here ...

NB : I used forms.ModelChoiceField in the code but you can use other supported form field.

  • Related