I want to display initial values as selected on a MultipleChoice form field in Django when the form loads. I populate a formset with different forms. Each form has only one field ‘answer’, which is initialized based on a custom parameter passed to the form’s init() method.
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_)
This renders the following HTML:
But it doesn’t get into the form’s cleaned_data. When I submit formset, the request.POST data goes into this view:
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'
The cleaned_data
does have the correct ‘answer’ value in the case of Radio, but in this case, it doesn’t contain the list of selected IDs which it should. I’ve checked that request.POST.getlist('form_#_answer')
does show the correct list of [‘1’, ‘3’] but it somehow doesn’t get into the formset’s cleaned_data. I’ve spent hours trying to find out why this happens. Can’t find the answer anywhere in the Django docs either. Can anyone explain why this is happening?