Login

Many2Many comma separated form field

Author:
haloween
Posted:
January 31, 2010
Language:
Python
Version:
1.1
Tags:
forms m2m comma many2many
Score:
0 (after 0 ratings)

Useful in sumbiting data . Remember to use form.save_m2m() :)

 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. Comma separated users field by sopelkin 7 years, 2 months ago
  2. MultiSelectField with comma separated values (Field + FormField) by quinode 2 years, 11 months ago
  3. Multiple Choice model field by danielroseman 6 years, 5 months ago
  4. MultipleEmailsField by spanasik 5 years, 12 months ago
  5. (en-US) Humanized Decimal Field by ActionScripted 6 years, 9 months ago

Comments

Please login first before commenting.