我正在研究多项选择题。 2个模型Question and Answers.i希望在一个表单集视图中同时处理这两个问题。但是,如果我从表单集中更改了多余的或max_num参数,则会收到“ ManagementForm数据丢失”的信息,然后得到“ MultiValueDict”对象没有属性“ pk”的信息。我无法解决问题。
class Question(models.Model):
subject = models.ForeignKey(Subject, on_delete=models.PROTECT)
topic = models.ForeignKey(Topic, on_delete=models.PROTECT)
desciption = models.TextField(max_length=700, null=False)
def __str__(self):
return "%s %s %s" % (self.desciption[:100],self.topic,self.subject)
class Answers(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
option = models.CharField(max_length=100)
is_true = models.BooleanField(default=False)
explaination = models.TextField(max_length=500, null=True ,blank=True)
def __str__(self):
return "%s" % (self.option)
我的forms.py
class QuestionForm(forms.ModelForm):
class Meta:
model = Question
fields = ('subject', 'topic', 'desciption')
class AnswerForm(forms.ModelForm):
class Meta:
model = Answers
fields = ('option', 'is_true', 'explaination')
exclude = ('question',)
def posttestq(request):
AnswerFormSet = inlineformset_factory(Question,Answers, form=AnswerForm, extra=4,max_num=4 )
data = {'form-TOTAL_FORMS': '4','form-INITIAL_FORMS': '0','form-MAX_NUM_FORMS': '4',}
if request.method == 'POST':
question_form = QuestionForm(request.POST, prefix='question')
answer_formset = AnswerFormSet( data,
request.POST, request.FILES, prefix='answer')
if question_form.is_valid() : #and
if answer_formset.is_valid():
question = question_form.save()
print(question)
answer_formset = AnswerFormSet(
request.POST, request.FILES, prefix='answer', instance=question)
# I have to validate (again - so I'm confident) to access clean data
answer_formset.is_valid()
print(answer_formset)
answer_formset.save()
return redirect('post_list')
else:
return render(request, 'mcq/testq.html', {
'message': "Check your form",
'question_form': question_form,
'answer_formset': answer_formset,
})
else:
question_form = QuestionForm(prefix='question')
answer_formset = AnswerFormSet( prefix='answer')
return render(request, 'mcq/testq.html', {
'question_form': question_form,
'answer_formset': answer_formset,
})
现在我得到了'MultiValueDict'对象,没有属性'pk'错误,但是如果我删除了“数据”参数“ ManagementForm数据丢失”
我的html文件是
<form action="" method="POST">
{% csrf_token %}
{{question_form.management_form}}
{% for answer_form in answer_formset %}
<br>
{{answer_form}}
{% endfor %}
<input type="submit" class="button btn-primary">
</form>