Reputation: 8982
I have tried quite a few things but I still don't know how can I populate a select field
in Django. The following example, adds a dictionary with a select field with a name='tags'
attribute.
data = {}
for tag in tags:
data['tags'] = tag.name
form = Form(initial=data)
As it is expected, the loop is overwriting the key 'tags', so it only prevails the last value (and indeed, the form shows the last value). I expected that maybe passing a list would work:
data = {}
l = []
for tag in tags:
l.append(tag.name)
data['tags'] = l
form = Form(initial=data)
But in this case, it just doesn't work.
As you can imagine, I'm using a form similar to this:
class NewTopicForm(forms.Form):
... some fields
tags = ChoiceField(
widget=forms.Select(),
choices=SOME_CHOICES
)
What is the correct way to populate a form with a select field when I need to add several values?.
Thanks!
UPDATE:
I tried the following in accordance with this post:
data = {'tags': tags.values_list('name',flat=True) }
Unfortunately, it doesn't work. Am I missing something?.
Upvotes: 0
Views: 2287
Reputation: 11464
It seems that you want MultipleChoiceField if you want the initial values to be a list.
Upvotes: 2