From 4101b57b1984af7f63eb5c7832861c30f2e7642d Mon Sep 17 00:00:00 2001
From: ClairePhila <ClairePhila@byom.de>
Date: Fri, 10 Feb 2017 18:28:16 +0100
Subject: [PATCH] [1.11.x] Refs #27148 -- Fixed UUIDField.to_python(None)
 crash.

Regression in 2f9861d823620da7ecb291a8f005f53da12b1e89.

Backport of d26413113c1a5c95218fe4e43a684a2fe1ad1bff from master
---
 django/db/models/fields/__init__.py |  2 +-
 tests/model_fields/test_uuid.py     | 13 ++++++++++++-
 2 files changed, 13 insertions(+), 2 deletions(-)

diff --git a/django/db/models/fields/__init__.py b/django/db/models/fields/__init__.py
index b7d60f9921..f695b33e35 100644
--- a/django/db/models/fields/__init__.py
+++ b/django/db/models/fields/__init__.py
@@ -2387,7 +2387,7 @@ class UUIDField(Field):
         return value.hex
 
     def to_python(self, value):
-        if not isinstance(value, uuid.UUID):
+        if value is not None and not isinstance(value, uuid.UUID):
             try:
                 return uuid.UUID(value)
             except (AttributeError, ValueError):
diff --git a/tests/model_fields/test_uuid.py b/tests/model_fields/test_uuid.py
index 5c87e4b0af..bc1c8d5bc0 100644
--- a/tests/model_fields/test_uuid.py
+++ b/tests/model_fields/test_uuid.py
@@ -54,13 +54,16 @@ class TestSaveLoad(TestCase):
             UUIDModel.objects.create(field='not-a-uuid')
 
 
-class TestMigrations(SimpleTestCase):
+class TestMethods(SimpleTestCase):
 
     def test_deconstruct(self):
         field = models.UUIDField()
         name, path, args, kwargs = field.deconstruct()
         self.assertEqual(kwargs, {})
 
+    def test_to_python(self):
+        self.assertIsNone(models.UUIDField().to_python(None))
+
 
 class TestQuerying(TestCase):
     def setUp(self):
@@ -88,6 +91,10 @@ class TestSerialization(SimpleTestCase):
         '[{"fields": {"field": "550e8400-e29b-41d4-a716-446655440000"}, '
         '"model": "model_fields.uuidmodel", "pk": null}]'
     )
+    nullable_test_data = (
+        '[{"fields": {"field": null}, '
+        '"model": "model_fields.nullableuuidmodel", "pk": null}]'
+    )
 
     def test_dumping(self):
         instance = UUIDModel(field=uuid.UUID('550e8400e29b41d4a716446655440000'))
@@ -98,6 +105,10 @@ class TestSerialization(SimpleTestCase):
         instance = list(serializers.deserialize('json', self.test_data))[0].object
         self.assertEqual(instance.field, uuid.UUID('550e8400-e29b-41d4-a716-446655440000'))
 
+    def test_nullable_loading(self):
+        instance = list(serializers.deserialize('json', self.nullable_test_data))[0].object
+        self.assertIsNone(instance.field)
+
 
 class TestValidation(SimpleTestCase):
     def test_invalid_uuid(self):