goinnn/django-multiselectfield

IndexError: list assignment index out of range

ramonyaskal opened this issue ยท 4 comments

self.validators[0] = MaxValueMultiFieldValidator(self.max_length)
IndexError: list assignment index out of range

django==4.1.1
django-multiselectfield==0.1.12

I see the same error after upgrading from django 4.0.7 to 4.1.2. This is a show-stopper.

Hello everyone,

@ramonyaskal @mortenthansen : Same here ๐Ÿ‘‹๐Ÿผ
I fixed the issue by adding a max_length to my MultiSelectField.

Hopes this will help you all.

I have the same issue here.

Python=3.8.16
Django==4.2.1
django-multiselectfield==0.1.12

And, probably, setting max_length will solve my case too.

Happy to work on this issue if that's ok with the maintainers.

pe712 commented

Indeed we have :

class  (Field):
    description = _("String (up to %(max_length)s)")

    def __init__(self, *args, db_collation=None, **kwargs):
        super().__init__(*args, **kwargs)
        self.db_collation = db_collation
        if self.max_length is not None:
            self.validators.append(validators.MaxLengthValidator(self.max_length))
class MultiSelectField(models.CharField):
    """ Choice values can not contain commas. """

    def __init__(self, *args, **kwargs):
        self.min_choices = kwargs.pop('min_choices', None)
        self.max_choices = kwargs.pop('max_choices', None)
        super(MultiSelectField, self).__init__(*args, **kwargs)
        self.max_length = get_max_length(self.choices, self.max_length)
        self.validators[0] = MaxValueMultiFieldValidator(self.max_length)

We see that MultiSelectField init passes max_length to CharField init. The MaxLengthValidator is only appended to self.validators if max_length not None. This causes the error.

In all cases, max_length is later set to get_max_length so the value we pass is deleted.

Moreover, max_length, is the length of the varchar in the database. And in the database the field is stored as AM,HE,PE for example. So max_length is the length of all the fields concatenated. Which is exactly what get_max_length returns.

To sum up, we should not need to specify max_length in most cases. The package should be modified so that if max_length is None, it is set to get_max_length AND the MaxLengthValidator is appended.