Django Form ChoiceField pass parameter for database query

I want to create a Django Form ChoiceField. The choices will be queried from an external database and should be filtered by a parameter {company_id}. How to pass this parameter?

views.py

` if request.method == 'GET':

company_id = 1 site_id = 3

return render(request, 'sites/new-column.html', { 'company_id': company_id, 'site_id': site_id, 'form_newcolumn': NewColumn(company_id), })`

forms.py

class NewColumn(forms.Form):

    def __init__(self, *args, **kwargs):
        company_id = kwargs.pop('company_id')
        super(NewColumn, self).__init__(args, kwargs)
        self.company_id = company_id  # Add it as an instance variable

    engine = db.engine("Database")
    connection = engine.raw_connection()
    cursor = connection.cursor()
    cursor.execute(f"SELECT * FROM table WHERE id = '{company_id}' ; ")
    all_rows = cursor.fetchall()

    choices = forms.ChoiceField(
        choices=[(row[0], row[1]) for row in all_rows],
        help_text='Make your Choice'
    )

How to pass {company_id} to query only the necessary choices?

I have found a solution for me at:

Django Form ChoiceField set choices in View in Form initial

I put the select statement an set the form "choices" and "initial" in views.py without using any def init in class definition.

Back to Top