我需要验证内联formset是否具有唯一值。 这个想法是能够添加一个问题和多个答案的竞争。我们可以使用复选框标记正确的答案,但是我需要确保选择或保存的复选框不超过一个。 我已经尝试在模型端使用clean()进行验证,并且还通过扩展BaseInlineFormSet,但是我似乎很难迭代formset并获得任何值。
class Competition(models.Model):
title = models.CharField(max_length=255)
slug = models.SlugField(unique=True, blank=False)
content = models.TextField()
terms = models.TextField()
class Question(models.Model):
competition = models.OneToOneField(
Competition,
on_delete=models.CASCADE,
primary_key=True,
)
question = models.CharField(max_length=255)
class Answer(models.Model):
question = models.ForeignKey(Question)
answer = models.CharField(max_length=255)
is_correct = models.BooleanField(default=False)
答案 0 :(得分:2)
所以经过一夜的睡眠后,我似乎已经设法解决了这个问题
from django.forms.models import BaseInlineFormSet
from django.core.exceptions import ValidationError
class AnswerInlineFormSet(BaseInlineFormSet):
def clean(self):
super(AnswerInlineFormSet, self).clean()
total_checked = 0
for form in self.forms:
if not form.is_valid():
return
if form.cleaned_data and not form.cleaned_data.get('DELETE'):
if form.cleaned_data['is_correct']:
total_checked += 1
if total_checked > 1:
raise ValidationError("You cannot have more than one correct answer")
if total_checked < 1:
raise ValidationError("You must have at least one correct answer")