Search code examples
pythondjangoformset

How to supply choices to a formset, if choices come from queryset or other view logic?


How to supply choices to a formset, if choices come from queryset or other view logic?

I have formset setup in forms.py as following:

class MCQuestionAnswerForm(forms.Form):
    question = forms.CharField()
    mcq_answer_choice = forms.ChoiceField(widget=forms.RadioSelect)


MCQuestionAnswerFormSet = formset_factory(MCQuestionAnswerForm, extra=0)

I need to supply in views.py different set of choices to the formset instance, where choices will be a result of a queryset or other view logic. Can I use for that matter form_kwargs? If so, how can I do that?

Edit:

Sorry, I was not clear about choices I want to alter. The choices is the initial parameter in the mcq_answer_choice field

    class MCQuestionAnswerForm(forms.Form):
    question = forms.CharField()
    mcq_answer_choice = forms.ChoiceField(widget=forms.RadioSelect, choices=SOME_CHOICES_LIST)

SOME_CHOICES_LIST will be supplied in views.py. Is this possible?


Solution

  • From the official documentation

    class MCQuestionAnswerForm(forms.Form):
         question = forms.CharField()
         mcq_answer_choice = forms.ChoiceField(widget=forms.RadioSelect)
    
         def __init__(self, *args, **kwargs):
             self.extra = kwargs.pop('extra')
             super(MyArticleForm, self).__init__(*args, **kwargs)
    
             # You have now use the value of self.extra to construct or alter your form body
             # For example:
             self.fields['mcq_answer_choice'].initial = self.extra
    
    MCQuestionAnswerFormSet = formset_factory(MCQuestionAnswerForm, extra=0)