[Fixed]-Django: Validator for a multiple choice form field

1👍

My guess is that value, returned by CheckboxSelectMultiple‘s value_from_datadict method, is list [u'abc', u'xyz']. Then it is converted to string [u'abc', u'xyz'] by field’s to_python method (actually, it is u"[u'abc', u'xyz']"). After validators are run. Length of this string is more than 3, that’s why you got ValidationError.

You should use ManyToManyField.

👤f43d65

0👍

The reason why my validator wasn’t working as intended was because the argument passed to the validator, say [u'abc', u'xyz'], was a string and not a list as I earlier thought while defining my validator. As a result, as rightly pointed out by @f43d65, the length of the argument exceeded 3 every single time, and hence the ValidationError was being raised.

I made the following changes in my validator in order for it to work as intended:

def len_area(li):
    if li.count("u'") > 3:
        raise ValidationError("Please select a maximum of three fields only")

Leave a comment