diff options
| author | Russell Keith-Magee <russell@keith-magee.com> | 2010-12-05 04:47:19 +0000 |
|---|---|---|
| committer | Russell Keith-Magee <russell@keith-magee.com> | 2010-12-05 04:47:19 +0000 |
| commit | 4a1f2129d09658e705fbe0660275c6efccf1474a (patch) | |
| tree | 196aec05eddaacbe7b4257d20ae3b4264f035b2c /django | |
| parent | ee48da24050a4f447f6ba153430c59b93a1522b3 (diff) | |
Fixed #12398 -- Added a TypedMultipleChoiceField. Thanks to Tai Lee.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@14829 bcc190cf-cafb-0310-a4f2-bffc1f526a37
Diffstat (limited to 'django')
| -rw-r--r-- | django/forms/fields.py | 30 |
1 files changed, 28 insertions, 2 deletions
diff --git a/django/forms/fields.py b/django/forms/fields.py index a0b559319b..d0a93cf0a6 100644 --- a/django/forms/fields.py +++ b/django/forms/fields.py @@ -40,7 +40,7 @@ __all__ = ( 'BooleanField', 'NullBooleanField', 'ChoiceField', 'MultipleChoiceField', 'ComboField', 'MultiValueField', 'FloatField', 'DecimalField', 'SplitDateTimeField', 'IPAddressField', 'FilePathField', 'SlugField', - 'TypedChoiceField' + 'TypedChoiceField', 'TypedMultipleChoiceField' ) def en_format(name): @@ -700,7 +700,7 @@ class TypedChoiceField(ChoiceField): def to_python(self, value): """ - Validate that the value is in self.choices and can be coerced to the + Validates that the value is in self.choices and can be coerced to the right type. """ value = super(TypedChoiceField, self).to_python(value) @@ -742,6 +742,32 @@ class MultipleChoiceField(ChoiceField): if not self.valid_value(val): raise ValidationError(self.error_messages['invalid_choice'] % {'value': val}) +class TypedMultipleChoiceField(MultipleChoiceField): + def __init__(self, *args, **kwargs): + self.coerce = kwargs.pop('coerce', lambda val: val) + self.empty_value = kwargs.pop('empty_value', []) + super(TypedMultipleChoiceField, self).__init__(*args, **kwargs) + + def to_python(self, value): + """ + Validates that the values are in self.choices and can be coerced to the + right type. + """ + value = super(TypedMultipleChoiceField, self).to_python(value) + super(TypedMultipleChoiceField, self).validate(value) + if value == self.empty_value or value in validators.EMPTY_VALUES: + return self.empty_value + new_value = [] + for choice in value: + try: + new_value.append(self.coerce(choice)) + except (ValueError, TypeError, ValidationError): + raise ValidationError(self.error_messages['invalid_choice'] % {'value': choice}) + return new_value + + def validate(self, value): + pass + class ComboField(Field): """ A Field whose clean() method calls multiple Field clean() methods. |
