[Answer]-Django form for 2 related model

1👍

This:

bform = MCAnswersForm(request.POST, instance=MCQuestions)

should be:

bform = MCAnswersForm(request.POST, instance=answers)

where answers is an instance of MCAnswers. There is no answer yet in your view (you are about to create it) so just remove it from your code for now.


You will need to add prefixes to your forms so the validation will work properly and you better give meaningful names to these (not aform)

    question_form = MCQuestionsForm(request.POST, prefix="question")
    answer_form = MCAnswersForm(request.POST, prefix="answers")

Finally to save, do this – you are missing the link from the question to the answer:

  if question_form.is_valid() and answer_form.is_valid():
        question = question_form.save(commit=False)
        question.qcategory_id = course_id
        question.save()

        answer = bform.save(commit=False)
        answer.question = question
        answer.save()

        return HttpRedirect(reverse('...'))

Leave a comment