[Answered ]-Django โ€“ how to force user to select a certain amount of options in a checbox modelform?

1๐Ÿ‘

โœ…

You can override the clean method of the form to check if between two and three BooleanFields 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 booleans and uses 0 for False, and 1 for True, it thus counts the number of Trues. If that number is not between 2 and 3, then it raises a ValidationError.

Leave a comment