[Answered ]-Django Form error "Enter a list of values" for ManyToMany field

2👍

It may be because from template i’m passing the “string” which will be a value of select option but in the ManyToMany filed it is required to save the ‘id’ which should be an integer.

You’re close. It’s expecting a list, not a single string. Below is the method to_python for the MultipleChoiceField.

def to_python(self, value):
    if not value:
        return []
    elif not isinstance(value, (list, tuple)):
        raise ValidationError(self.error_messages['invalid_list'])
    return [smart_unicode(val) for val in value]

Knowing now that you need a list, you can try to subclass the MultipleChoiceField and provide your own to_python:

class SingleMultipleChoiceField(MultipleChoiceField):
    widget = Select

    def to_python(self, value):
        if not value:
            return []
        return [value]

    def validate(self, value):
        if self.required and not value:
            raise ValidationError(self.error_messages['required'])
        if not self.valid_value(value):
            raise ValidationError(self.error_messages['invalid_choice'] % {'value': value})

I haven’t tested this, but give it a shot. Or, ideally, just use the standard widget instead of the Select widget, and this whole issue goes away. I’m not sure why you’re trying to force only a single element into a ManyToManyField; they are built for multiple objects.

Leave a comment