Exemple #1
0
    def to_db_value(
            self, value: Optional[datetime.datetime],
            instance: "Union[Type[Model], Model]"
    ) -> Optional[datetime.datetime]:

        # Only do this if it is a Model instance, not class. Test for guaranteed instance var
        if hasattr(instance, "_saved_in_db") and (
                self.auto_now or
            (self.auto_now_add
             and getattr(instance, self.model_field_name) is None)):
            value = timezone.now()
            setattr(instance, self.model_field_name, value)
            return value
        if value is not None:
            if get_use_tz():
                if timezone.is_naive(value):
                    warnings.warn(
                        "DateTimeField %s received a naive datetime (%s)"
                        " while time zone support is active." %
                        (self.model_field_name, value),
                        RuntimeWarning,
                    )
                    value = timezone.make_aware(value, "UTC")
        self.validate(value)
        return value
Exemple #2
0
 def to_python_value(self, value: Any) -> Optional[datetime.datetime]:
     if value is None:
         return value
     if isinstance(value, datetime.datetime):
         datetime_value = value
     elif isinstance(value, int):
         datetime_value = datetime.datetime.fromtimestamp(value)
     else:
         datetime_value = parse_datetime(value)
     if timezone.is_naive(datetime_value):
         datetime_value = timezone.make_aware(datetime_value,
                                              get_timezone())
     else:
         datetime_value = localtime(datetime_value)
     return datetime_value