0

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?.

Community
  • 1
  • 1
r_31415
  • 8,752
  • 17
  • 74
  • 121

1 Answers1

2

It seems that you want MultipleChoiceField if you want the initial values to be a list.

Skylar Saveland
  • 11,116
  • 9
  • 75
  • 91
  • 1
    Beautiful. I had to change it to tags = forms.MultipleChoiceField( widget=forms.SelectMultiple(attrs={ // some attributes }), choices=TAGS_CHOICES), but that worked perfectly. Thanks a lot!. – r_31415 May 23 '12 at 05:26