Django-为form.MultipleChoiceField设置初始选定值

时间:2020-08-30 18:53:33

标签: django django-forms

我想显示在加载表单时在Django中的MultipleChoice表单字段上选择的初始值。我用不同的表单填充表单集。每个表单只有一个字段“ answer”,该字段根据传递给表单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:

Checkbox rendered

但是它没有进入表单的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确实具有正确的“ answer”值,但是在这种情况下,它不包含应该选择的ID列表。我已经检查了该请求。POST.getlist('form _#_ answer')确实显示了['1','3']的正确列表,但不知何故不进入表单集的cleaned_data。我花了几个小时试图找出原因。在Django文档中也找不到任何答案。谁能解释为什么会这样?

0 个答案:

没有答案
相关问题