如何在第一种方法(contect_data)的第二种方法(表格)中获得变量qid。
现在我收到错误: NameError:name' tmp'未定义
class AnswerView(FormView):
template_name = 'answer.html'
form_class = AnsForm
success_url='success'
def get_context_data(self, *args, **kwargs):
context = super(AnswerView,self).get_context_data(**kwargs)
qid = self.kwargs['qid']
print(qid)
self.qid=qid
q_obj = Quest.objects.get(id=qid)
context['question'] = q_obj
return context
def form_valid(self, form):
answ1 = form.cleaned_data['txta']
tmp = self.get_context_data().qid
obj4=Ans.objects.create(answer=answ1,status=0,questid=tmp)
obj4.save()
return super().form_valid(form)
答案 0 :(得分:2)
实际上,您也可以在self.kwargs['qid']
中使用form_valid
。所以你可以这样做:
class AnswerView(FormView):
template_name = 'answer.html'
form_class = AnsForm
success_url='success'
def get_context_data(self, *args, **kwargs):
context = super(AnswerView,self).get_context_data(**kwargs)
qid = self.kwargs['qid']
q_obj = Quest.objects.get(id=qid)
context['question'] = q_obj
return context
def form_valid(self, form):
answ1 = form.cleaned_data['txta']
tmp = self.kwargs['qid']
obj4=Ans.objects.create(answer=answ1,status=0,questid=tmp)
obj4.save()
return super().form_valid(form)
答案 1 :(得分:0)
这样做的一种方法是将变量qid设置为您班级的数据成员,尽管我不确定这是否适合您的用例。这样两种方法都可以访问和修改它。希望这能解决你的问题。