Login

Many2Many comma separated form field

Author:
haloween
Posted:
January 31, 2010
Language:
Python
Version:
1.1
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. Template tag - list punctuation for a list of items by shapiromatron 10 months, 3 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

Please login first before commenting.