Reputation: 1765
I'm trying to populate in my template a <select>
element with data from a form field like this:
forms.py
class CreatePlayerForm(forms.Form):
size = forms.CharField()
views.py
class CreatePlayer(FormView):
...
def get(self, request, *args, **kwargs):
...
boots = Boots.objects.filter(...).values_list('size', flat=True) # return a list
form.initial['boots'] = boots
template
<select id="leftValues4" size="5" multiple>
{% for boot in form.boots %}
<option>{{ boot }}</option>
{% endfor %}
</select>
With the above code I don't get any results.
Any suggestion?
Upvotes: 0
Views: 2620
Reputation: 599876
You are not approaching this in the right way at all.
initial
is specifically for pre-setting the chosen value. You are trying to populate the list of values. For that, you will need to use an actual field that supports such a list; and that is a ChoiceField, not a CharField.
Secondly, choices need to have an ID value as well as a display value; so you need a list/tuple of 2-tuples.
form:
class CreatePlayerForm(forms.Form):
size = forms.ChoiceField(choices=[])
def __init__(self, *args, **kwargs):
sizes = kwargs.pop('sizes')
super(CreatePlayerForm, self).__init__(*args, **kwargs)
self.fields['sizes'].choices = sizes
view:
class CreatePlayer(FormView):
...
def get_form_kwargs(self, *args, **kwargs):
form_kwargs = super(CreatePlayer, self).get_form_kwargs(*args, **kwargs)
boots = Boots.objects.filter(...).values_list('id', 'size')
form_kwargs['sizes'] = boots
return form_kwargs
template:
{{ form.boots }}
Upvotes: 1