views:

27

answers:

1

All the answers I've seen to this so far have confused me.

I've made a form that gets built dynamically depending on a parameter passed in, and questions stored in the database. This all works fine (note: it's not a ModelForm, just a Form).

Now I'm trying to save the user's responses. How can I iterate over their submitted data so I can save it?

The MultipleChoiceFields are confusing me especially. I'm defining them as:

self.fields['question_' + str(question.id)] = forms.MultipleChoiceField(
                label=mark_safe(required_tag +
                    question.label + "<br/>Choose any of the following answers"),
                help_text=question.description,
                required=question.required,
                choices=choices,
                widget=widgets.CheckboxSelectMultiple())

When I select several options, the actual posted data is something like:

question_1=5&question_1=6

Will django automatically realise that these are both options on the same form and let me access an iterable somewhere? I was going to do something like:

for field in self.cleaned_data:
        print field      # save the user's response somehow

but this doesn't work since this will only return question_1 once, even though there were two submitted values.

Answer: The for loop now works as expected if I loop through self.fields instead of self.cleaned_data:

for field in self.fields:
    print self.cleaned_data[field]
A: 

... this doesn't work ...

Are you sure? Have you tested it? Normally the cleaned_data value for a MultipleChoiceField is a list of the values chosen on the form.

So yes, it only returns question_1 once, but that returned value itself contains multiple values.

Daniel Roseman
ah yes, it does work. i needed to make a little tweak. thanks - wasn't sure if i was heading in the right direction.
Roger