Reputation: 605
I want to make forms that submit individually these 2 models. Somehow i managed to get views for them. However, i got error saying:
unbound method full_clean() must be called with MCQuestions instance as first argument (got nothing instead)
my details are:
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})
and error is highlighting bform_valid = bform.is_valid()
Upvotes: 0
Views: 163
Reputation: 5496
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('...'))
Upvotes: 1