瀏覽代碼

Fixed #17294 -- Supported nullable DateTimeFields when time zone support is enabled. Thanks pressureman for the report.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@17148 bcc190cf-cafb-0310-a4f2-bffc1f526a37
Aymeric Augustin 13 年之前
父節點
當前提交
866c229f52

+ 1 - 1
django/db/models/fields/__init__.py

@@ -786,7 +786,7 @@ class DateTimeField(DateField):
 
     def get_prep_value(self, value):
         value = self.to_python(value)
-        if settings.USE_TZ and timezone.is_naive(value):
+        if value is not None and settings.USE_TZ and timezone.is_naive(value):
             # For backwards compatibility, interpret naive datetimes in local
             # time. This won't work during DST change, but we can't do much
             # about it, so we let the exceptions percolate up the call stack.

+ 3 - 0
django/utils/timezone.py

@@ -228,6 +228,9 @@ def now():
     else:
         return datetime.now()
 
+# By design, these four functions don't perform any checks on their arguments.
+# The caller should ensure that they don't receive an invalid value like None.
+
 def is_aware(value):
     """
     Determines if a given datetime.datetime is aware.

+ 3 - 0
tests/modeltests/timezones/models.py

@@ -3,6 +3,9 @@ from django.db import models
 class Event(models.Model):
     dt = models.DateTimeField()
 
+class MaybeEvent(models.Model):
+    dt = models.DateTimeField(blank=True, null=True)
+
 class Timestamp(models.Model):
     created = models.DateTimeField(auto_now_add=True)
     updated = models.DateTimeField(auto_now=True)

+ 6 - 1
tests/modeltests/timezones/tests.py

@@ -25,7 +25,7 @@ from django.utils.tzinfo import FixedOffset
 from django.utils.unittest import skipIf
 
 from .forms import EventForm, EventSplitForm, EventModelForm
-from .models import Event, Timestamp
+from .models import Event, MaybeEvent, Timestamp
 
 
 # These tests use the EAT (Eastern Africa Time) and ICT (Indochina Time)
@@ -403,6 +403,11 @@ class NewDatabaseTests(BaseDateTimeTests):
                  datetime.datetime(2011, 1, 1, tzinfo=UTC)],
                 transform=lambda d: d)
 
+    def test_null_datetime(self):
+        # Regression for #17294
+        e = MaybeEvent.objects.create()
+        self.assertEqual(e.dt, None)
+
 NewDatabaseTests = override_settings(USE_TZ=True)(NewDatabaseTests)