from django.forms.models import ModelMultipleChoiceField from django.forms.widgets import TextInput from django.forms.util import ValidationError from django.utils.encoding import force_unicode class ModelMultipleCommaField(ModelMultipleChoiceField): widget = TextInput def clean(self,value): if self.required and not value: raise ValidationError(self.error_messages['required']) elif not self.required and not value: return [] value=value.split(',') if not isinstance(value, (list, tuple)): raise ValidationError(self.error_messages['list']) for pk in value: try: self.queryset.filter(pk=pk) except ValueError: raise ValidationError(self.error_messages['invalid_pk_value'] % pk) qs = self.queryset.filter(pk__in=value) pks = set([force_unicode(o.pk) for o in qs]) for val in value: if force_unicode(val) not in pks: raise ValidationError(self.error_messages['invalid_choice'] % val) return qs