初始数据作为formset外键字段的查询集

时间:2016-01-26 07:37:25

标签: django django-forms formset

我正在研究英语语言测试应用程序。每个问题都有问题和4个可能的答案。只有一个答案是正确的。 以下是模型:

class EnglishTestQuestion(AbstractDatetimeModel):
    text = models.CharField(max_length=255, verbose_name=u"Question text")

class EnglishTestAnswerVariants(models.Model):
    question = models.ForeignKey(EnglishTestQuestion, verbose_name=_(u"question"), related_name='Variants')
    text = models.CharField(max_length=255, verbose_name=u"Text")
    is_correct = models.BooleanField(_(u"Is correct"), default=False)

class EnglishTestAnswer(AbstractDatetimeModel):
    user = models.ForeignKey(User, blank=True, null=True, verbose_name=u"user")
    question = models.ForeignKey(EnglishTestQuestion, blank=False, verbose_name=u"question")
    answer = models.ForeignKey(EnglishTestAnswerVariants, verbose_name=u"answer")

这是观点。我为每个问题创建一个表单并传递初始数据。问题字段获取初始数据,但是“答案”字段忽略它并显示所有答案,:

def english_test(request):
    questions = EnglishTestQuestion.objects.all()
    QuestionFormSet = formset_factory(form=EnglishTestForm, max_num=questions.count())
    formset = QuestionFormSet(initial=[{
                                           'question': x,
                                           'answer': EnglishTestAnswerVariants.objects.filter(question=x)
                                       } for x in questions])

    return render(request, 'testing/english_test.html', {"questions": questions, "question_formset": formset})

但它应该只显示每个问题通过外键连接的答案。

这是表格:

class EnglishTestForm(forms.ModelForm):

    class Meta:
        model = EnglishTestAnswer
        fields = '__all__'
        widgets = {
            'answer': forms.RadioSelect()
        }

如何仅在答案字段中传递那些与FK问题相关的答案?

1 个答案:

答案 0 :(得分:2)

initial参数传递字段的初始,而不传递这些字段的可用选项。在您的情况下,您可以动态调整EnglishTestForm.answer字段的查询集:

class EnglishTestForm(forms.ModelForm):
    class Meta:
        model = EnglishTestAnswer
        fields = '__all__'
        widgets = {
            'answer': forms.RadioSelect()
        }

    def __init__(self, *args, **kwargs):
        super(EnglishTestForm, self).__init__(*args, **kwargs)
        question = self.initial.get('question')
        if question:
            self.fields['answer'].queryset = question.Variants.all()

P.S。:实际上你有一个安全问题:恶意用户可以伪造你的formset值,例如,制作四个具有相同问题ID和所有可能答案ID的表单。当您盲目保存这些表格时,根据您的计算方法,它可能会导致测试的误报结果。只是为了警告你。