Issue
I'd like to populate a form dropdown with data from database. Those data don't come directly from a model but from a raw query.
This is working when the database is available and the migrations are already generated. Otherwise, generating the migrations (python manage.py makemigrations myapp
) fails because Django evaluates _all_departments()
which is not able to find the appropriate table.
def _all_departments() -> List[Tuple[str, str]]:
from django.db import connection
with connection.cursor() as cursor:
cursor.execute("select distinct department from crm_mytable order by department")
return [(row[0], row[0]) for row in cursor.fetchall()]
class MyForm(forms.Form):
department = forms.CharField(
widget=forms.SelectMultiple(choices=_all_departments()))
I naively tried to update manually the choices on __init__
without success (choices are always empty):
class MyForm(forms.Form):
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['department'].widget.choices = _all_departments()
department = forms.CharField(
widget=forms.SelectMultiple(choices=[]))
What would be the way to properly fill on-demand the choices?
Solution
You should not pass the choices
to the widget, but to the field. You furthermore probably want to use a MultipleChoiceField
[Django-doc], this uses a SelectMultiple
[Django-doc] as default widget:
class MyForm(forms.Form):
department = forms.MultipleChoiceField(choices=[])
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['department'].choices = _all_departments()
Answered By - Willem Van Onsem
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.