Created
April 24, 2012 23:54
-
-
Save chopachom/2484723 to your computer and use it in GitHub Desktop.
ModelMultipleCommaField
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ModelMultipleCommaField(forms.ModelMultipleChoiceField): | |
widget = forms.TextInput | |
def __init__(self, queryset, db_lookup_field='pk', *args, **kwargs): | |
super(ModelMultipleCommaField, self).__init__(queryset, *args, **kwargs) | |
self.db_lookup_field = db_lookup_field | |
def clean(self,value): | |
if self.required and not value: | |
raise ValidationError(self.error_messages['required']) | |
elif not self.required and not value: | |
return [] | |
values=[x.strip() for x in value.split(',')] | |
if not isinstance(values, (list, tuple)): | |
raise ValidationError(self.error_messages['list']) | |
for value in values: | |
try: | |
self.queryset.filter(**{self.db_lookup_field:values}) | |
except ValueError: | |
raise ValidationError(self.error_messages['invalid_choice'] % value) | |
qs = self.queryset.filter(**{self.db_lookup_field+'__in':values}) | |
existing_values = set([ | |
force_unicode(getattr(o, self.db_lookup_field)) for o in qs | |
]) | |
for val in values: | |
if force_unicode(val) not in existing_values: | |
raise ValidationError(self.error_messages['invalid_choice'] % val) | |
return qs |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment