I'm new to Django and struggling to find the best/correct way to populate a dropdown list in a ModelChoiceField within a form using a list I have stored in a database. The basic code below works fine with my view passing the form as context to my template but the drop-down returns a 'dictionary' like list with the ugliness or the brackets, colons and the key name (see the attachment)
from django import forms
from .models import constituency
class ConstituencyForm(forms.Form):
ConstituencySelection = forms.ModelChoiceField(queryset=constituency.objects.all().values('name'))
My questions are:
1/ The purpose of this page will be to select one of 650 areas from the dropdown list and have it highlighted on the map. Is this an appropriate way to approach the task (using a queryset within the form itself)?
2/ How do I clean up this list, it should simply read:-
Aldershot
Aldridge-Brownhills
Altrincham and Sale West
and so on and so on
Your help would be forever appreciated!
Thanks,
Phil #anoobinneed
Using values_list() with flat=True
will do it.
Change:
queryset=constituency.objects.all().values('name')
To:
queryset=constituency.objects.all().values_list('name', flat=True)