Ejemplo n.º 1
0
    def from_native(self, value):
        if value in validators.EMPTY_VALUES:
            return None

        if isinstance(value, datetime.datetime):
            if timezone and settings.USE_TZ and timezone.is_aware(value):
                # Convert aware datetimes to the default time zone
                # before casting them to dates (#17742).
                default_timezone = timezone.get_default_timezone()
                value = timezone.make_naive(value, default_timezone)
            return value.date()
        if isinstance(value, datetime.date):
            return value

        for format in self.input_formats:
            if format.lower() == ISO_8601:
                try:
                    parsed = parse_date(value)
                except (ValueError, TypeError):
                    pass
                else:
                    if parsed is not None:
                        return parsed
            else:
                try:
                    parsed = datetime.datetime.strptime(value, format)
                except (ValueError, TypeError):
                    pass
                else:
                    return parsed.date()

        msg = self.error_messages['invalid'] % readable_date_formats(
            self.input_formats)
        raise ValidationError(msg)
Ejemplo n.º 2
0
    def from_native(self, value):
        if value in validators.EMPTY_VALUES:
            return None

        if isinstance(value, datetime.datetime):
            if timezone and settings.USE_TZ and timezone.is_aware(value):
                # Convert aware datetimes to the default time zone
                # before casting them to dates (#17742).
                default_timezone = timezone.get_default_timezone()
                value = timezone.make_naive(value, default_timezone)
            return value.date()
        if isinstance(value, datetime.date):
            return value

        for format in self.input_formats:
            if format.lower() == ISO_8601:
                try:
                    parsed = parse_date(value)
                except (ValueError, TypeError):
                    pass
                else:
                    if parsed is not None:
                        return parsed
            else:
                try:
                    parsed = datetime.datetime.strptime(value, format)
                except (ValueError, TypeError):
                    pass
                else:
                    return parsed.date()

        msg = self.error_messages['invalid'] % readable_date_formats(self.input_formats)
        raise ValidationError(msg)
 def default(self, o):
     # For Date Time string spec, see ECMA 262
     # http://ecma-international.org/ecma-262/5.1/#sec-15.9.1.15
     if isinstance(o, Promise):
         return force_text(o)
     elif isinstance(o, datetime.datetime):
         r = o.isoformat()
         if o.microsecond:
             r = r[:23] + r[26:]
         if r.endswith('+00:00'):
             r = r[:-6] + 'Z'
         return r
     elif isinstance(o, datetime.date):
         return o.isoformat()
     elif isinstance(o, datetime.time):
         if timezone and timezone.is_aware(o):
             raise ValueError("JSON can't represent timezone-aware times.")
         r = o.isoformat()
         if o.microsecond:
             r = r[:12]
         return r
     elif isinstance(o, datetime.timedelta):
         return str(o.total_seconds())
     elif isinstance(o, decimal.Decimal):
         return str(o)
     elif hasattr(o, 'tolist'):
         return o.tolist()
     elif hasattr(o, '__iter__'):
         return [i for i in o]
     return super(JSONEncoder, self).default(o)
Ejemplo n.º 4
0
 def default(self, o):
     # A dictionary may have a date as it's key, explicitly handle this
     if isinstance(o, dict):
         result = {}
         for key, value in o.iteritems():
             result[self.default(key)] = self.default(value)
         return result
     # For Date Time string spec, see ECMA 262
     # http://ecma-international.org/ecma-262/5.1/#sec-15.9.1.15
     elif isinstance(o, Promise):
         return force_text(o)
     elif isinstance(o, (geometry.LineString, geometry.MultiLineString,
                         geometry.MultiPoint, geometry.MultiPolygon,
                         geometry.Point, geometry.Polygon)):
         return o.__geo_interface__
     elif isinstance(o, datetime.datetime):
         r = o.isoformat()
         if o.microsecond:
             r = r[:23] + r[26:]
         if r.endswith('+00:00'):
             r = r[:-6] + 'Z'
         return r
     elif isinstance(o, datetime.date):
         return o.isoformat()
     elif isinstance(o, datetime.time):
         if timezone and timezone.is_aware(o):
             raise ValueError("JSON can't represent timezone-aware times.")
         r = o.isoformat()
         if o.microsecond:
             r = r[:12]
         return r
     elif isinstance(o, datetime.timedelta):
         return str(o.total_seconds())
     elif isinstance(o, decimal.Decimal):
         return str(o)
     elif hasattr(o, 'tolist'):
         return o.tolist()
     elif hasattr(o, '__iter__'):
         return [self.default(i) for i in o]
     else:
         return o
Ejemplo n.º 5
0
    def from_native(self, value):
        if value in validators.EMPTY_VALUES:
            return None

        if isinstance(value, datetime.datetime):
            if timezone and settings.USE_TZ and timezone.is_aware(value):
                # Convert aware datetimes to the default time zone
                # before casting them to dates (#17742).
                default_timezone = timezone.get_default_timezone()
                value = timezone.make_naive(value, default_timezone)
            return value.date()
        if isinstance(value, datetime.date):
            return value

        try:
            parsed = parse_date(value)
            if parsed is not None:
                return parsed
        except ValueError:
            msg = self.error_messages["invalid_date"] % value
            raise ValidationError(msg)

        msg = self.error_messages["invalid"] % value
        raise ValidationError(msg)
Ejemplo n.º 6
0
    def from_native(self, value):
        if value in validators.EMPTY_VALUES:
            return None

        if isinstance(value, datetime.datetime):
            if timezone and settings.USE_TZ and timezone.is_aware(value):
                # Convert aware datetimes to the default time zone
                # before casting them to dates (#17742).
                default_timezone = timezone.get_default_timezone()
                value = timezone.make_naive(value, default_timezone)
            return value.date()
        if isinstance(value, datetime.date):
            return value

        try:
            parsed = parse_date(value)
            if parsed is not None:
                return parsed
        except ValueError:
            msg = self.error_messages['invalid_date'] % value
            raise ValidationError(msg)

        msg = self.error_messages['invalid'] % value
        raise ValidationError(msg)