I've got this model :
class QuestionInstance(models.Model):
questionsSet = models.ForeignKey(QuestionsSet)
question = models.ForeignKey(Question)
parent = models.ForeignKey('self',null=True,blank=True)
optional = models.BooleanField(default=False)
I'd like to create a dropdown, which user could choose one QuestionInstance. It has to be filtered with questionsSet.
I've tested using a modelform like this, but it's not working :
(based on this How do I filter values in a Django form using ModelForm?)
class FormQuestionSelect(ModelForm):
instanceList = forms.ChoiceField(choices=[(questionInstance.id, questionInstance.question) for questionInstance in QuestionInstance.objects.all()])
class Meta:
model = QuestionInstance
fields = ('instanceList', )
widgets = {
'instanceList': Select(attrs={'class': 'select'}),
}
def __init__(self, questionsSet=None, **kwargs):
super(FormQuestionSelect, self).__init__(**kwargs)
if questionsSet:
#Tested many code here to filter, None of them worked :(
#Is that possible to create instanceList there ?
I'm not sure using a modelform is a good idea for this kind of purpose.
A modelform is great when create or update a model instance. When using specific forms, like in this case, I'm using a custom form in template :
View
questionInstanceList = QuestionInstance.objects.filter(questionsSet=questionsSet)
Template
<select name="questionInstanceSelect">
{% for instance in questionInstanceList %}
<option value="{{ instance.id }}">{{ instance.question.text }}</option>
{% endfor %}
</select>
and process them this way :
instanceList = request.POST.get('questionInstanceSelect')
I'm quite sure there's a proper way.
QuestionSetby user without form submit?Questionforeignkey to be filtered based on selectedQuestionSet. Am I correct?