anders
anders

Reputation: 81

How do I make a list for a drop down menu in django?

The title may be a bit obscure. I am trying to produce a drop-down menu in django based on the following code:

class MyForm(forms.Form):
   person_list = PersonYear.objects.all().values('person__pk', 'person__TLA')
   person = forms.CharField(label='Säljare',widget = 
            forms.Select(choices=person_list))

I was trying this, because my understanding is that I need a list of the form

person_list = [(1 , 'Abc'), (2, 'CDe'),...]

but my person_list has the form

<QuerySet [{'person_pk : '1', 'person_TLA : 'Abc'}, {'person_pk : '2', 
'person_TLA : 'CDe'}].......>

So it does not work. How should I be doing this. I want to get a drop-down menu with the TLA:s from which I then can identify the pk.

Upvotes: 1

Views: 43

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599470

You should use forms.ModelChoiceField for this. It takes a queryset and you don't need to customise the widget.

person = forms.ModelChoiceField(label='Säljare', queryset=PersonYear.objects.all())

Upvotes: 1

Related Questions