如何在Django的基于函数的视图中设置外键?

时间:2018-12-09 19:20:27

标签: django django-models

这是错误-无法分配“'question2'”:“ Answers.question”必须是“ Question”实例。

model.py

def main(request, pk):
ques = get_object_or_404(Question, pk=pk)
if request.method == "POST":
    answerForm = AnswerForm(request.POST)
    if answerForm.is_valid():
        ans = answerForm.save(commit=False)
        ans.user = request.user
        ans.question = Answers(question=ques.question) # here assigning foreign key
        ans.answer = answerForm.cleaned_data.get['question_sel']
        print(answerForm.cleaned_data.get['question_sel'])
        ans.save()
        return redirect('main', pk=ques.pk)
else:
    answerForm = AnswerForm(request.POST)
return render(request, 'quiz/main.html', {'ques': ques,'answerForm':answerForm})

1 个答案:

答案 0 :(得分:0)

您可能只想在这里ans.question = quesques是当前问题的实例,该问题将保存到答案中。

如果您想获得一个特定问题的答案,则需要做Answer.objects.get(question=ques),但这在这种情况下没有意义。