django - Django - 为 formd.MultipleChoiceField 设置初始选定值
问题描述
我想在表单加载时显示在 Django 中的 MultipleChoice 表单字段上选择的初始值。我用不同的表单填充表单集。每个表单只有一个字段“答案”,它是根据传递给表单的 init() 方法的自定义参数进行初始化的。
class AnswerForm(forms.Form):
def __init__(self, *args, **kwargs):
"""
Initialize label & field
:returns None:
"""
question = kwargs.pop('question') # A Question object
super(AnswerForm, self).__init__(*args, **kwargs)
if question.type == Types.RADIO:
choices_ = [(op.id, op) for op in question.option_set.all()]
self.fields['answer'] = forms.ChoiceField(label=question.statement,
initial=1,
widget=forms.RadioSelect,
choices=choices_)
elif question.type == Types.CHECKBOX:
choices_ = [(op.id, op) for op in question.option_set.all()]
self.fields['answer'] = forms.MultipleChoiceField(label=question.statement,
initial=[1,3],
widget=forms.CheckboxSelectMultiple,
choices=choices_)
这将呈现以下 HTML:
但它不会进入表单的cleaned_data。当我提交表单集时,request.POST 数据进入此视图:
def post(self, request, form_id):
"""
Process & save the responses obtained from a form into DB
:param request: An HTTPRequest object
:param form_id: form id whose responses arrive
:returns HttpResponse object with a results template
"""
formset = FormHandler.AnswerFormSet(request.POST, request.FILES,
form_kwargs={'questions': FormHandler.qs})
if formset.is_valid():
for form in formset:
cd = form.cleaned_data
# Access cd['answer'] here but cd appears to be empty dict {}
# with no key named 'answer'
在 Radio的cleaned_data
情况下,它确实具有正确的“答案”值,但在这种情况下,它不包含它应该包含的选定 ID 列表。我检查了 request.POST.getlist('form_#_answer') 确实显示了正确的 ['1', '3'] 列表,但它不知何故没有进入表单集的clean_data。我花了几个小时试图找出为什么会发生这种情况。在 Django 文档中的任何地方都找不到答案。谁能解释为什么会这样?
解决方案
推荐阅读
- swift - 从自定义 SKSpriteNode 类设置 SKSpriteNodes 位置
- reactjs - 使用 createMuiTheme() 的 Material-UI 自定义主题不起作用
- google-colaboratory - 在google colab中上传kaggle.json文件时出错
- weblogic12c - 在 weblogic server 中文档的元素内容中发现了一个无效的 XML 字符 (Unicode: 0x0)
- javascript - 如何区分两个相同类型的游戏手柄?
- tomcat - 为 Peppol 安装 Oxalis AS4
- ruby-on-rails - 如何为每个模型添加新列?
- angular - 无法读取未定义的属性“_lastPathIndex”
- mysql - NodeJS Express REST API 插入 MYSQL 错误
- java - 在 Java 中编写“.shape”等价物