class SwithchedValueTypedChoiceField(MultipleChoiceField): """ Return selected data as value instead of value html ttribute. """ def to_python(self, value): if not value: return [] elif not isinstance(value, (list, tuple)): raise ValidationError(self.error_messages['invalid_list']) def switched(value, choices): """ Switched value generator """ count = 0 max_count = len(value) while count < max_count: yield choices[value[count]] count += 1 value = list(switched(value, dict(self._choices))) return value def valid_value(self, value): "Check to see if the provided value is a valid choice" for k, v in self.choices: if isinstance(v, (list, tuple)): # This is an optgroup, so look inside the group for options for k2, v2 in v: if value == smart_unicode(v2): return True else: if value == smart_unicode(v): return True return False