diff --git a/django/contrib/mongodb/base.py b/django/contrib/mongodb/base.py index 54552b8a03..1e5529d98d 100644 --- a/django/contrib/mongodb/base.py +++ b/django/contrib/mongodb/base.py @@ -76,8 +76,9 @@ class DatabaseWrapper(BaseDatabaseWrapper): return self.connection[self.settings_dict["NAME"]] def close(self): - self._connection.disconnect() - self._connection = None + if self._connection is not None: + self._connection.disconnect() + self._connection = None ########################### diff --git a/tests/regressiontests/mongodb/tests.py b/tests/regressiontests/mongodb/tests.py index a39aec29d1..c87a4b18d4 100644 --- a/tests/regressiontests/mongodb/tests.py +++ b/tests/regressiontests/mongodb/tests.py @@ -1,3 +1,4 @@ +from django.db import connection from django.db.models import Count, F from django.test import TestCase @@ -337,3 +338,8 @@ class MongoTestCase(TestCase): ], lambda g: g.name, ) + + def test_close(self): + # Ensure that closing a connection that was never established doesn't + # blow up. + connection.close()