如果选项来自queryset或其他视图逻辑,如何向表单集提供choices
?
我在forms.py
中设置了formset,如下所示:
class MCQuestionAnswerForm(forms.Form):
question = forms.CharField()
mcq_answer_choice = forms.ChoiceField(widget=forms.RadioSelect)
MCQuestionAnswerFormSet = formset_factory(MCQuestionAnswerForm, extra=0)
我需要在views.py
不同的choices
集合中提供formset实例,其中choices
将是查询集或其他视图逻辑的结果。我可以使用form_kwargs吗?如果是这样,我该怎么做?
修改
抱歉,我不清楚choices
我想改变。 choices
是mcq_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
中提供。这可能吗?
答案 0 :(得分:1)
来自官方文档
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)