我有以下型号:
class Question(models.Model):
name = RichTextField (
verbose_name = 'Question'
)
QUESTION_TYPE = (
('Multi', 'Multiple Choice (one correct answer)'),
('Check', 'Multiple Answers')
)
question_type = models.CharField(
default = "Multi",
max_length = 7,
verbose_name = "Question Type",
choices = QUESTION_TYPE)
category = models.ForeignKey(
Category,
help_text = 'Category for this Question',
null = True
)
author = models.ForeignKey(
User,
)
quiz = models.ForeignKey (
Quiz,
)
def __unicode__(self):
return u'%s' % (self.name)
我正在尝试使用Django表单,所以我有这样的形式:
class QuestionForm(forms.ModelForm):
class Meta:
model = Question
fields = ['id','question_type','category','name','author','quiz',]
widgets = {'id': forms.HiddenInput(),
'author': forms.HiddenInput(),
'quiz': forms.HiddenInput(),
'name': forms.TextInput(attrs={'class': 'form-control'}),
'question_type' :forms.Select(attrs={'class': 'form-control'}),
'category' :forms.Select(attrs={'class': 'form-control'}),
}
除了类别模型与特定测验相关联之外,它工作正常,我只想要问题所链接的测验的类别。
class Category(models.Model):
name = models.CharField (
max_length = 30,
verbose_name = "Question Categories",
)
quiz = models.ForeignKey (
Quiz,
verbose_name = 'Quiz',
)
def __unicode__(self):
return u'%s' % (self.name)
我正在尝试研究如何限制通过表单呈现给用户的Category
模型,但我无法弄清楚如何。非常感谢。
答案 0 :(得分:0)
您可以尝试以下内容:
q_info = Question.objects.get(id=question_id)
Q = QuestionForm(instance=q_info)
Q.fields['category'].queryset = Category.objects.filter(condition)