首页 > 解决方案 > 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 文档中的任何地方都找不到答案。谁能解释为什么会这样?

标签: djangodjango-forms

解决方案


推荐阅读