0

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'))

I want just the area name in this dropdown list

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

4

1 回答 1

0

使用values_list()可以flat=True做到这一点。

改变:

queryset=constituency.objects.all().values('name')

至:

queryset=constituency.objects.all().values_list('name', flat=True)
于 2020-01-26T05:23:55.310 回答