Я работаю над приложением викторины и использую Django для бэкенда и Materialise для фронтэнда.
в функции просмотра смена вопроса с использованием inlineformset_factory в модели ответа
model.py
class Answer(models.Model):
question = models.ForeignKey(QuestionModel, on_delete=models.CASCADE, related_name='answers')
text = models.CharField('Answer', max_length=255)
is_correct = models.BooleanField('Correct answer', default=False)
def __str__(self):
return self.text
forms.py
class BaseAnswerInlineFormSet(forms.BaseInlineFormSet):
DELETE =forms.BooleanField()
is_correct =forms.BooleanField()
def clean(self):
super().clean()
has_one_correct_answer = False
for form in self.forms:
if not form.cleaned_data.get('DELETE', False):
if form.cleaned_data.get('is_correct', False):
has_one_correct_answer = True
break
if not has_one_correct_answer:
raise ValidationError('Mark at least one answer as correct.', code='no_correct_answer')
views.py
def question_change(request, question_pk):
question = get_object_or_404(QuestionModel, pk=question_pk)
AnswerFormSet = inlineformset_factory(
QuestionModel, # parent model
Answer, # base model
formset=BaseAnswerInlineFormSet,
fields=('text', 'is_correct'),
min_num=2,
validate_min=True,
max_num=8,
validate_max=True
)
if request.method == 'POST':
form = QuestionForm(request.POST, instance=question)
formset = AnswerFormSet(request.POST, instance=question)
if form.is_valid() and formset.is_valid():
with transaction.atomic():
form.save()
formset.save()
messages.success(request, 'Question and answers saved with success!')
return redirect('questions:question_list')
else:
form = QuestionForm(instance=question)
formset = AnswerFormSet(instance=question)
return render(request, 'question/question_change_form.html', {
'question': question,
'form': form,
'formset': formset
})
uestion_change_form.html
введите описание изображения здесь
выход -
с basefile, показывающим вот так с base.html, показывающим вот так и флажок не показывающий
без base.html, показывающего флажок
флажок, показанный здесь