1👍
✅
You need to implement it in the __init__
method.
This is my suggestion:
class AnswerForm(ModelForm):
class Meta:
model = ProjectQuestionnaireAnswer
fields = ('answer','notes')
widgets = {
'notes': forms.Textarea(attrs={'class': 'form-control','placeholder': 'Add notes to question here'}),
}
def __init__(self, *args, **kwargs):
question_id = kwargs.pop('question_id')
super().__init__(*args, **kwargs)
self.fields['answer'] = forms.ModelChoiceField(
queryset=Choice.objects.filter(question_id=question_id),
widget=forms.Select(attrs={'class': 'form-control select2'})
)
Then when initializing the form, you need to pass to it the question_id
argument. For the example in the post: AnswerForm(question_id=1)
Let me know if that works.
Source:stackexchange.com