Reputation: 113
I need to validate that an inline formset has a unique value. The idea is to be able to add a competition with a question and multiple answers. We can flag the correct answer using a checkbox, however I need to ensure that no more than one checkbox is ever selected or saved. I have tried validating with a clean() on the model side and also by extending BaseInlineFormSet, but then I seem to struggle to iterate over the formset and get any values.
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)
Upvotes: 2
Views: 1820
Reputation: 113
So after a nights sleep I appear to have managed to fix it
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")
Upvotes: 2