Many2Many comma separated form field

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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

More like this

  1. ManyToManyField no syncdb by powerfox 3 years, 4 months ago
  2. ModelForm Class saving m2m by ckarrie2 7 months, 2 weeks ago
  3. unique_together with many to many fields by j4nu5 8 months, 1 week ago
  4. ManyToManyField with maximum cardinality constraints by gsakkis 1 year, 11 months ago
  5. How to connect m2m_changed sent by specific senders for symmetrical m2ms by ilikefm 6 months, 3 weeks ago

Comments

(Forgotten your password?)