我无法弄清楚如何指定ModelChoiceField
的初始选择。我有什么警告吗?
class QuizUserForm(forms.Form):
question = forms.CharField()
eq_answer = forms.CharField(widget=forms.Textarea)
def __init__(self, *args, **kwargs):
super(QuizUserForm, self).__init__(*args, **kwargs)
self.fields['mcq_answer_choice'] = forms.ModelChoiceField(queryset=models.MCQChoice.objects.filter(
question__prompt=kwargs['initial']['question']), initial=1, widget=forms.RadioSelect,
empty_label=None)
答案 0 :(得分:1)
尝试将initial
设置为等于模型实例。最好在类级别指定字段并更新__init__
class QuizUserForm(forms.Form):
question = forms.CharField()
eq_answer = forms.CharField(widget=forms.Textarea)
mcq_answer_choice = forms.ModelChoiceField(
queryset=models.MCQChoice.objects.none(),
widget=forms.RadioSelect,
empty_label=None
)
def __init__(self, *args, **kwargs):
super(QuizUserForm, self).__init__(*args, **kwargs)
queryset = models.MCQChoice.objects.filter(
question__prompt=kwargs['initial']['question']
)
self.fields['mcq_answer_choice'].queryset = queryset
self.fields['mcq_answer_choice'].initial = queryset.first()