我有这个模型:
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)
我想创建一个下拉列表,用户可以选择一个 QuestionInstance。它必须用 questionsSet 过滤。
我已经使用这样的模型进行了测试,但它不起作用:
(基于此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 ?
我不确定使用模型表单是否适合这种目的。
在创建或更新模型实例时,模型表单非常有用。在使用特定表单时,例如在这种情况下,我在模板中使用自定义表单:
看法
questionInstanceList = QuestionInstance.objects.filter(questionsSet=questionsSet)
模板
<select name="questionInstanceSelect">
{% for instance in questionInstanceList %}
<option value="{{ instance.id }}">{{ instance.question.text }}</option>
{% endfor %}
</select>
并以这种方式处理它们:
instanceList = request.POST.get('questionInstanceSelect')
我很确定有一个正确的方法。