开发者

Processing dynamic MultipleChoiceField in django

开发者 https://www.devze.com 2023-01-12 07:40 出处:网络
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 fin

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 doe开发者_Go百科sn'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]


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

0

精彩评论

暂无评论...
验证码 换一张
取 消