在django中处理动态的MultipleChoiceField [英] Processing dynamic MultipleChoiceField in django

查看:113
本文介绍了在django中处理动态的MultipleChoiceField的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止,我看到的所有答案让我感到困惑。



我已经根据传入的参数和存储在数据库中的问题制作了动态构建的表单。这一切都很好(注意:它不是一个ModelForm,只是一个Form)。



现在我试图保存用户的响应。如何迭代他们提交的数据,以便我可以保存它?



MultipleChoiceFields特别令我困惑。我定义为:

  self.fields ['question_'+ str(question.id)] = forms.MultipleChoiceField (
label = mark_safe(required_tag +
question.label +< br />选择以下答案之一),
help_text = question.description,
= question.required,
choices = choices,
widget = widgets.CheckboxSelectMultiple())

当我选择几个选项时,实际发布的数据类似于:

  question_1 = 5& question_1 = 6 

将django自动认识到这两个选项在同一个表单上,让我访问一个迭代的地方?我将要执行以下操作:

  for self.cleaned_data:
print field#保存用户的响应不知何故

但这不工作,因为这只会返回 question_1 一次,即使有两个提交的值。



答案:for循环现在按照预期工作,如果我循环 self.fields 而不是 self.cleaned_data

  for self.fields中的字段:
print self.cleaned_data [field]


解决方案


...这不工作...


你确定吗?你测试了吗通常,MultipleChoiceField的 clean_data 值是表单上选择的值的列表。



所以是的,它只返回question_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]

解决方案

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

这篇关于在django中处理动态的MultipleChoiceField的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆