Django Form ChoiceField pass parameter for database query
Verfasst: Dienstag 31. Januar 2023, 10:26
Für ein Django Form form.ChoiceField würde ich gerne die Auswahlmöglichkeiten aus einer externen Datenbank filtern über eine Parameter 'company_id'. Ich habe Schwierigkeiten beim durchschleifen dieses Parameter, ohne diesen konnte ich schon alle Inhalte der Datenbank als Auswahl anfügen, bitte um Hilfe:
views.py
forms.py
In def __init__ kann man den parameter 'company_id' ansprechen, außerhalb im SELECT statement leider nicht, Select Statement könnte man auch in die def __init__ packen, allerdings bekomme ich 'all_rows' auch nicht in forms.ChoiceField(); bitte um Hilfestellung Danke
views.py
Code: Alles auswählen
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=company_id
),
})
forms.py
Code: Alles auswählen
class NewColumn(forms.Form):
def __init__(self, *args, **kwargs):
company_id = kwargs.get('company_id')
print(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'
)