SaidAkh SaidAkh - 11 days ago 6
Python Question

Specify initial choice for a form `ModelChoiceField`

I cannot figure out how to specify initial choice for

ModelChoiceField
. Is there any caveat that I am missing?

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)

Answer

Try setting initial equal to model instance. Also it is better, to specify field on class level and update params in __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()