Django形式为2相关模型

时间:2015-06-06 17:06:28

标签: python django forms model

我想制作单独提交这2个模型的表单。不知怎的,我设法为他们获得了意见。但是,我得到错误说:

  

未绑定方法full_clean()必须使用MCQuestions实例作为第一个参数调用(没有任何内容)

我的详细信息是:

models.py

class MCQuestions(models.Model):
    question = FroalaField(null=True, blank=True)
    qcategory = models.ForeignKey(Categories, related_name="MCCategory", blank=True)


class MCAnswers(models.Model):
    questionid = models.ForeignKey(MCQuestions, related_name="mc_answer")
    a = models.CharField(max_length=50, null=True, blank=True)
    z_a = models.BooleanField(default=False)
    b = models.CharField(max_length=50, null=True, blank=True)
    z_b = models.BooleanField(default=False)
    c = models.CharField(max_length=50, null=True, blank=True)
    z_c = models.BooleanField(default=False)
    d = models.CharField(max_length=50, null=True, blank=True)
    z_d = models.BooleanField(default=False)

views.py

 def AddMCQuestions(request, course_id):
    if request.method == 'POST':
        aform = MCQuestionsForm(request.POST)
        bform = MCAnswersForm(request.POST, instance=MCQuestions)
        #cat = Categories.objects.filter(cid=course_id)
        aform_valid = aform.is_valid()
        **bform_valid = bform.is_valid()**
        if aform_valid and bform_valid:
            a = aform.save(commit=False)
            a.qcategory_id = course_id
            a.save()
            b = bform.save(commit=False)
            b.save()
            return HttpResponse('question added')
    else:
        aform = MCQuestionsForm()
        bform = MCAnswersForm()
        bform.qcategoryid = a
   return render(request, 'teacher/mcquestionadd.html', {'aform': aform, 'bform': bform})

错误突出显示bform_valid = bform.is_valid()

1 个答案:

答案 0 :(得分:1)

此:

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

应该是:

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

其中answersMCAnswers的实例。您的视图中还没有答案(您即将创建它),所以暂时将其从代码中删除。

您需要在表单中添加前缀,以便验证正常运行,最好为这些提供有意义的名称(不是aform

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

最后要保存,请执行此操作 - 您错过了从问题到答案的链接:

  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('...'))