Я работаю над вопросом с несколькими вариантами ответов. 2 модель Вопрос и Ответы. Я хочу обрабатывать оба в одном представлении формы. но я получил «Данные ManagementForm отсутствуют», если я изменил параметр extra или max_num из formset, то я получил «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)
my 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', но если я уберу параметр "data", данные ManagementForm отсутствуют "
my 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>