如果选择来自查询集或其他视图逻辑,如何向表单集提供选择?

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

如果选择来自查询集或其他视图逻辑,如何向表单集提供 choices

我在 forms.py 中设置了以下格式集:

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


MCQuestionAnswerFormSet = formset_factory(MCQuestionAnswerForm, extra=0)

我需要在 views.py 中向表单集实例提供不同的 choices 集,其中 choices 将是查询集或其他视图逻辑的结果。我可以使用 form_kwargs 吗?如果可以,我该怎么做?

编辑:

对不起,我不清楚choices我要修改。 choicesmcq_answer_choice 字段中的初始参数

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

SOME_CHOICES_LIST 将在 views.py 中提供。这可能吗?

来自官方文档

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)