django 在访问 self.initial 中的字段时引发 KeyError

django raising KeyError when accessing to field in self.initial

我编写了一个名为 AnswerForm 的表单。这种形式用于从问题的选择中得到答案。(选择和问题是模型)。这是我的 AnswerForm 代码:​​

class AnswerForm(forms.Form):
    question = forms.ModelChoiceField(queryset=Question.objects.all(),
                                      required=True,
                                      widget=forms.HiddenInput(attrs={"class": "hidden-input"}))

    def __init__(self, *args, **kwargs):
        super(AnswerForm, self).__init__(*args, **kwargs)
        self.fields['answer'] = forms.ModelChoiceField(queryset=self.initial["question"].choice_set.all(),
                                                       required=False,
                                                       widget=ExamChoiceInput)



    def clean_question(self):
        return self.initial["question"]

我在表单集中使用此表单,这样用户可以一次回答很多问题。但是,当用户发送表单时,init 第二行中的 self.initial["question"] 会引发 KeyError 值。 (我已经打印了 self.initial 并且它完全是空的)。这是我使用 post 方法处理请求的函数:

def process_saving_form(request):
    if request.method == "POST":
        current_user = request.user
        AnswerFormSet = formset_factory(AnswerForm)
        formset = AnswerFormSet(request.POST)

        if formset.is_valid():
            for form in formset:
                new_user_madechoice = MadeChoice(
                            user=current_user,
                            choice=form.cleaned_data["answer"]
                        )
                try:
                    current_user_madechoice = current_user.madechoice_set.get(choice__question=form.cleaned_data["question"])
                    if current_user_madechoice.choice != form.cleaned_data["answer"]:
                        current_user_madechoice.delete()
                        new_user_madechoice.save()
                except MadeChoice.DoesNotExist:
                    new_user_madechoice.save()

你能告诉我这是什么问题吗?

问题是您没有将任何 initial 数据传递给您 AnswerFormSet

的答案中查看我是如何做到的:

initial = [{'question': q} for q in questions]
formset = AnswerFormSet(request.POST, initial=initial)