Converts the input single value into the expected Python data type,
        raising django.core.exceptions.ValidationError if the data can't be
        converted.  Returns the converted value. Subclasses should override
        this.
1383
def value_to_python(self, value):
        
        if not isinstance(value, bytes):
            raise tldap.exceptions.ValidationError("should be a bytes")

        try:
            value = int(value)
        except (TypeError, ValueError):
            raise tldap.exceptions.ValidationError("is invalid integer")

        try:
            value = datetime.date.fromtimestamp(value * 24 * 60 * 60)
        except OverflowError:
            raise tldap.exceptions.ValidationError("is too big a date")

        return value
1254200
def convert(data):
    
    try:
        st = basestring
    except NameError:
        st = str
    if isinstance(data, st):
        return str(data)
    elif isinstance(data, Mapping):
        return dict(map(convert, data.iteritems()))
    elif isinstance(data, Iterable):
        return type(data)(map(convert, data))
    else:
        return data
1051532
def to_python(self):
        
        if isinstance(self.data, str):
            return self.data.strip().lower() == 'true'
        if isinstance(self.data, int):
            return self.data > 0
        return bool(self.data)
235013
def normalize(value, default=None, type=None, raise_exception=False):
    
    NUMBER_RE = re.compile('^[-+]?(([0-9]+\.?[0-9]*)|([0-9]*\.?[0-9]+))$')
    if type is None and default is None:
        type = unicode_type
    elif type is None:
        type = type_(default)
    if type in str_types:
        if value is not None:
            if isinstance(value, unicode_type):
                return value
            elif py3 and isinstance(value, bytes_type):
                return value.decode('utf-8')
            return unicode_type(value)
        if default is None:
            if raise_exception:
                raise ValidationError('invalid string')
            else:
                return unicode_type()
    elif type in (bool, 'bool', 'boolean'):
        if value is not None:
            value = value.lower().strip()
            if value in ('1', 'true', 'yes', 'on'):
                return True
            elif value in ('0', 'false', 'no', 'off'):
                return False
        if default is None:
            if raise_exception:
                raise ValidationError('invalid boolean')
            else:
                return False
    elif type in (numbers.Number, 'number'):
        if value is not None:
            if value.isdigit():
                return int(value)
            elif NUMBER_RE.match(value):
                return eval(value)
        if default is None:
            if raise_exception:
                raise ValidationError('invalid number')
            else:
                return 0
    elif type in (int, 'int', 'integer'):
        try:
            return int(value)
        except Exception:
            if isinstance(value, basestring_type) and NUMBER_RE.match(value):
                return int(eval(value))
            if default is None:
                if raise_exception:
                    raise ValidationError('invalid number')
                else:
                    return 0
    elif type in (float, 'float'):
        if value is not None and NUMBER_RE.match(value):
            return float(value)
        if default is None:
            if raise_exception:
                raise ValidationError('invalid number')
            else:
                return 0.0
    return default
856889
def validate(self, raw_data, **kwargs):
        
        try:
            converted_data = float(raw_data)
            super(FloatField, self).validate(converted_data, **kwargs)
            return raw_data
        except ValueError:
            raise ValidationException(self.messages['invalid'], repr(raw_data))
1338946
def to_python(self, value):
        """"""

        # ``is_required`` is already checked in ``validate``.
        if value is None:
            return None

        # Validate the type.
        if not isinstance(value, six.string_types):
            raise forms.ValidationError(
                "Invalid value type (should be a string).",
                code='invalid-choice-type',
            )

        # Get the constant from the choices object, raising if it doesn't exist.
        try:
            final = getattr(self.choices, value)
        except AttributeError:
            available = '[%s]' % ', '.join(self.choices.constants)
            raise forms.ValidationError(
                "Invalid value (not in available choices. Available ones are: %s" % available,
                code='non-existing-choice',
            )

        return final
597329
def validate(self, value):
        
        try:
            length = len(value)
        except TypeError:
            length = 0

        if self.min_length is not None:
            min_length = self.min_length() if callable(self.min_length) else self.min_length
            if length < min_length:
                raise exceptions.ValidationError(self.min_err.format(min_length))

        if self.max_length is not None:
            max_length = self.max_length() if callable(self.max_length) else self.max_length
            if length > max_length:
                raise exceptions.ValidationError(self.max_err.format(max_length))
1024412
def convert(self):
        

        if self.is_type():
            return self.force_convert()

        raise TypeConversionError(
            "failed to convert from {} to {}".format(type(self._data).__name__, self.typename)
        )
382580
def to_python(self, value):
        
        if value in validators.EMPTY_VALUES:
            return None
        if isinstance(value, datetime.datetime):
            return value.time()
        if isinstance(value, datetime.time):
            return value
        if isinstance(value, list):
            # Input comes from a 2 SplitTimeWidgets, for example. So, it's two
            # components: start time and end time.
            if len(value) != 2:
                raise ValidationError(self.error_messages['invalid'])
            if value[0] in validators.EMPTY_VALUES and value[1] in \
                    validators.EMPTY_VALUES:
                return None

            start_value = value[0]
            end_value = value[1]

        start_time = None
        end_time = None

        for format in self.input_formats or formats.get_format(\
                'TIME_INPUT_FORMATS'):
            try:
                start_time = datetime.datetime(
                    *time.strptime(start_value, format)[:6]
                ).time()
            except ValueError:
                if start_time:
                    continue
                else:
                    raise ValidationError(self.error_messages['invalid'])

        for format in self.input_formats or formats.get_format(\
                'TIME_INPUT_FORMATS'):
            try:
                end_time = datetime.datetime(
                    *time.strptime(end_value, format)[:6]
                ).time()
            except ValueError:
                if end_time:
                    continue
                else:
                    raise ValidationError(self.error_messages['invalid'])

        return (start_time, end_time)
332398
def to_python(self, value):
        
        if not value:
            value = []

        # If a list is set then validated its items
        if isinstance(value, list):
            py_list = self.validate_list(value)
        else:  # try to de-serialize value and expect list and then validate
            try:
                py_list = json.loads(value)

                if not isinstance(py_list, list):
                    raise TypeError

                self.validate_list(py_list)
            except (ValueError, TypeError):
                raise ValidationError(u'Must be a valid list of strings.')

        return py_list
90691
def to_python(self, value):
        
        if value in validators.EMPTY_VALUES:
            return None
        if isinstance(value, datetime.datetime):
            return value.date()
        if isinstance(value, datetime.date):
            return value
        if isinstance(value, list):
            # Input comes from a 2 SplitDateWidgets, for example. So, it's two
            # components: start date and end date.
            if len(value) != 2:
                raise ValidationError(self.error_messages['invalid'])
            if value[0] in validators.EMPTY_VALUES and value[1] in \
                    validators.EMPTY_VALUES:
                return None

            start_value = value[0]
            end_value = value[1]

        start_date = None
        end_date = None

        for format in self.input_formats or \
                formats.get_format('DATE_INPUT_FORMATS'):
            try:
                start_date = datetime.datetime(*time.strptime(start_value, \
                        format)[:6]).date()
            except ValueError:
                continue

        for format in self.input_formats or formats.get_format(\
                'DATE_INPUT_FORMATS'):
            try:
                end_date = datetime.datetime(
                    *time.strptime(end_value, format)[:6]
                ).date()
            except ValueError:
                continue

        return (start_date, end_date)
537226
def to_python(self, data):
        
        if data is None:
            return data
        if self.datatype:
            return self.datatype(data)
        else:
            return data
1250686
def to_python(self, value):
        
        if isinstance(value, type(re.compile(''))):
            return value
        else:
            if value is None and self.null:
                return None
            else:
                try:
                    return self.get_compiled_regex(value)
                except:
                    raise ValidationError('Invalid regex {0}'.format(value))
678642
def convert(self, value, view):
        
        if isinstance(value, BASESTRING):
            if self.pattern and not self.regex.match(value):
                self.fail(
                    u"must match the pattern {0}".format(self.pattern),
                    view
                )
            return value
        else:
            self.fail(u'must be a string', view, True)
496710
def val_factory(val, datatypes):
    
    exceptions = []
    for dt in datatypes:
        try:
            if isinstance(val, dt):
                return val
            return type_handler_object(val, dt)
        except Exception as e:
            exceptions.append(str(e))
    # if we get here, we never found a valid value. raise an error
    raise ValueError('val_factory: Unable to instantiate {val} from types {types}. Exceptions: {excs}'.
                     format(val=val, types=datatypes, excs=exceptions))
1147379
def validate(self, val):
        
        if not isinstance(val, six.string_types):
            raise ValidationError("'%s' expected to be a string, got %s"
                                  % (val, generic_type_name(val)))
        if not six.PY3 and isinstance(val, str):
            try:
                val = val.decode('utf-8')
            except UnicodeDecodeError:
                raise ValidationError("'%s' was not valid utf-8")

        if self.max_length is not None and len(val) > self.max_length:
            raise ValidationError("'%s' must be at most %d characters, got %d"
                                  % (val, self.max_length, len(val)))
        if self.min_length is not None and len(val) < self.min_length:
            raise ValidationError("'%s' must be at least %d characters, got %d"
                                  % (val, self.min_length, len(val)))

        if self.pattern and not self.pattern_re.match(val):
            raise ValidationError("'%s' did not match pattern '%s'"
                                  % (val, self.pattern))
        return val
905378
def to_internal_value(self, data):
        
        data = smart_text(data).strip()
        if len(data) > self.MAX_STRING_LENGTH:
            self.fail('max_string_length')

        try:
            value = decimal.Decimal(data)
        except decimal.DecimalException:
            self.fail('invalid')

        # Check for NaN. It is the only value that isn't equal to itself,
        # so we can use this to identify NaN values.
        if value != value:
            self.fail('invalid')

        # Check for infinity and negative infinity.
        if value in (decimal.Decimal('Inf'), decimal.Decimal('-Inf')):
            self.fail('invalid')

        return self.validate_precision(value)