0

所以这是我的表格:

class QuestionForm(forms.ModelForm):
    answer = forms.ChoiceField(required=True, widget=forms.RadioSelect())

    def __init__(self, question=None, *args, **kwargs):
        super(QuestionForm, self).__init__(*args, **kwargs)
        self.fields['answer'].choices = [(a.answer, a.answer) for a in Answer.objects.filter(question=question)]

    class Meta:
        model = Questions
        fields = ('answer', 'importance' )

当用户选择answer它时,它会显示所有Answer对象。以下是我的看法:

def questions(request):
    new_forms = []
    q = Questions.objects.all()[0]
    if request.method =='POST':
        #form = QuestionForm(request.POST or None)
        for forms in new_forms:
            if forms.is_valid():
                new = forms.save(commit=False)
                #get the user's inputs to the QuestionForm and save them
                UserAnswer(user=request.user, answer=new.cleaned_data['answer'], question=new.question)
                UserAnswer.save()

    else:
        instance=Questions.objects.all().filter(owner=request.user)[0]
        #form = QuestionForm(question=q, instance=q)

    for a in Questions.objects.all():
        new_forms.append(QuestionForm(question=a, instance=a))
    return render_to_response("questions/base.html", locals(), context_instance=RequestContext(request))
4

1 回答 1

1

我对你在做什么感到很困惑。

            print new.fields['id_answer_2'].value
            print get_id_answer_2_display()

save(commit=False)是一个返回模型实例的 ModelForm 。它甚至不应该有 fields 属性(你会在这里得到一个 AttributeError )。

2:你下一个get_id_answer_2_display()看起来甚至不是正确的领域的电话(不要介意你把它作为一个独立的函数来调用)。

您的 ModelForm 建议您有一个answer字段,因此要使用get_FOO_display,您需要调用new.get_answer_display()

于 2013-02-18T00:45:45.627 回答