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

时间:2015-01-09 00:43:43

标签: django django-forms django-models

我写了一个名为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"]

我在formset中使用此表单,因此用户可以一次回答许多问题。但是,当用户发送表单时,会在 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()

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

1 个答案:

答案 0 :(得分:1)

问题是您没有向initial传递任何AnswerFormSet数据。

your previous question的答案中了解我是如何做到的:

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