所以这是我的表格:
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))
答案 0 :(得分: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()