1๐
โ
You can override the clean
method of the form to check if between two and three BooleanField
s are checked:
from django.core.exceptions import ValidationError
class FruitPicker(ModelForm):
# โฎ
def clean(self, *args, **kwargs):
data = super().clean(*args, **kwargs)
total = sum([data[x] for x in ['banana', 'grape', 'apple', 'mango']])
if not (2 <= total <= 3):
raise ValidationError('You should select between 2 and 3 fruits.')
return data
Here the sum(โฆ)
sums up the bool
eans and uses 0
for False
, and 1 for True
, it thus counts the number of True
s. If that number is not between 2
and 3
, then it raises a ValidationError
.
Source:stackexchange.com