如果选择来自queryset或其他视图逻辑,如何为formset提供选择?

时间:2016-11-25 17:18:13

标签: python django formset

如果选项来自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我想改变。 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中提供。这可能吗?

1 个答案:

答案 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)